home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part1 / 56 < prev    next >
Encoding:
Text File  |  1996-08-05  |  252.8 KB  |  6,615 lines

  1. Newsgroups: comp.lang.c,comp.answers,news.answers
  2. Path: news.sprintlink.net!eskimo!scs
  3. From: scs@eskimo.com (Steve Summit)
  4. Subject: comp.lang.c Answers to Frequently Asked Questions (FAQ List)
  5. X-Nntp-Posting-Host: eskimo.com
  6. Message-ID: <1996Jan01.0301.scs.0001@eskimo.com>
  7. Followup-To: poster
  8. Originator: scs@eskimo.com
  9. Sender: news@eskimo.com (News User Id)
  10. Supersedes: <1995Dec01.0300.scs.0001@eskimo.com>
  11. Reply-To: scs@eskimo.com
  12. X-Pgp-Signature: Version: 2.6
  13.     iQCSAwUBMJfIlt6sm4I1rmP1AQEQkQPoj16ypMN3DfyPMd+dz+/fZbPBWBjKtU02
  14.     5hGQs/8NGMmBYBdUX6akBxHowF4fD3YSp8XkNxz6DbAXBsYdv2253NASEmvBG2Ak
  15.     6qFPZDHdJ7Efue7UlVpGFJsM7qsgrtrBkv6WIZo01DMv3omEhof+VMyxFd0J2fKZ
  16.     CLrPnyk=
  17.     =SCgY
  18. X-Archive-Name: C-faq/faq
  19. Organization: only when absolutely necessary
  20. X-Version: 3.1
  21. Date: Mon, 1 Jan 1996 11:04:58 GMT
  22. X-Last-Modified: November 1, 1995
  23. Approved: news-answers-request@MIT.Edu
  24. Expires: Sat, 3 Feb 1996 00:00:00 GMT
  25. X-Url: http://www.eskimo.com/~scs/C-faq.top.html
  26.  
  27. Archive-name: C-faq/faq
  28. Comp-lang-c-archive-name: C-FAQ-list
  29. URL: http://www.eskimo.com/~scs/C-faq.top.html
  30.  
  31. [Last modified November 1, 1995 by scs.]
  32.  
  33. This article is Copyright 1990-1995 by Steve Summit.  Content from the
  34. book _C Programming FAQs: Frequently Asked Questions_ is made available
  35. here by permission of the author and the publisher as a service to the
  36. community.  It is intended to complement the use of the published text
  37. and is protected by international copyright laws.  The content is made
  38. available here and may be accessed freely for personal use but may not
  39. be published or retransmitted without written permission.
  40.  
  41. WARNING: A major update to this FAQ list occured in September 1995.  All
  42. sections and questions were rearranged and renumbered.  If you're in the
  43. habit of referring people to "question m.n in the FAQ list" or even
  44. "section m in the FAQ list," they may be confused if they have a
  45. different version than the one you hold.  During the changeover, the
  46. safest way to refer people to sections is by name ("the section on
  47. memory allocation").  There isn't a good symbolic way to refer to a
  48. particular question, but if you mention what the question is about, your
  49. recipient should be able to find it.  See the diff list posted along
  50. with this FAQ list for a correspondence between old and new sections
  51. and question numbers.
  52.  
  53.             *    *    *
  54.  
  55. Certain topics come up again and again on this newsgroup.  They are good
  56. questions, and the answers may not be immediately obvious, but each time
  57. they recur, much net bandwidth and reader time is wasted on repetitive
  58. responses, and on tedious corrections to the incorrect answers which are
  59. inevitably posted.
  60.  
  61. This article, which is posted monthly, attempts to answer these common
  62. questions definitively and succinctly, so that net discussion can move
  63. on to more constructive topics without continual regression to first
  64. principles.
  65.  
  66. No mere newsgroup article can substitute for thoughtful perusal of a
  67. full-length tutorial or language reference manual.  Anyone interested
  68. enough in C to be following this newsgroup should also be interested
  69. enough to read and study one or more such manuals, preferably several
  70. times.  Some C books and compiler manuals are unfortunately inadequate;
  71. a few even perpetuate some of the myths which this article attempts to
  72. refute.  Several noteworthy books on C are listed in this article's
  73. bibliography; see also question 18.10.  Many of the questions and
  74. answers are cross-referenced to these books, for further study by the
  75. interested and dedicated reader (but beware of ANSI vs. ISO C Standard
  76. section numbers; see question 11.1).
  77.  
  78. If you have a question about C which is not answered in this article,
  79. first try to answer it by checking a few of the referenced books, or by
  80. asking knowledgeable colleagues, before posing your question to the net
  81. at large.  There are many people on the net who are happy to answer
  82. questions, but the volume of repetitive answers posted to one question,
  83. as well as the growing number of questions as the net attracts more
  84. readers, can become oppressive.  If you have questions or comments
  85. prompted by this article, please reply by mail rather than following up --
  86. this article is meant to decrease net traffic, not increase it.
  87.  
  88. Besides listing frequently-asked questions, this article also summarizes
  89. frequently-posted answers.  Even if you know all the answers, it's worth
  90. skimming through this list once in a while, so that when you see one of
  91. its questions unwittingly posted, you won't have to waste time
  92. answering.
  93.  
  94. This article was last modified on November 1, 1995, and its travels
  95. may have taken it far from its original home on Usenet.  It may now
  96. be out-of-date, particularly if you are looking at a printed copy or one
  97. retrieved from a tertiary archive site or CD-ROM.  You can always obtain
  98. the most up-to-date copy by anonymous ftp from sites ftp.eskimo.com,
  99. rtfm.mit.edu, or ftp.uu.net (see questions 18.16 and 20.40), or by
  100. sending the e-mail message "help" to mail-server@rtfm.mit.edu .  Since
  101. this list is modified from time to time, its question numbers may not
  102. match those in older or newer copies which are in circulation; be
  103. careful when referring to FAQ list entries by number alone.
  104.  
  105. This article was produced for free redistribution.  You should not need
  106. to pay anyone for a copy of it.
  107.  
  108. Other versions of this document are also available.  Posted along with
  109. it are an abridged version and (when there are changes) a list of
  110. differences with respect to the previous version.  A
  111. hypertext version is available on the world-wide web (WWW); see URL
  112. <http://www.eskimo.com/~scs/C-faq.top.html>.  Finally, for those who
  113. might prefer a bound, hardcopy version (and even longer answers to even
  114. more questions!), a book-length version is being published by Addison-
  115. Wesley and should appear in November, 1995 (ISBN 0-201-84519-9).
  116.  
  117. This article is always being improved.  Your input is welcomed.  Send
  118. your comments to scs@eskimo.com .
  119.  
  120. The questions answered here are divided into several categories:
  121.  
  122.      1. Declarations and Initializations
  123.      2. Structures, Unions, and Enumerations
  124.      3. Expressions
  125.      4. Pointers
  126.      5. Null Pointers
  127.      6. Arrays and Pointers
  128.      7. Memory Allocation
  129.      8. Characters and Strings
  130.      9. Boolean Expressions and Variables
  131.     10. C Preprocessor
  132.     11. ANSI/ISO Standard C
  133.     12. Stdio
  134.     13. Library Functions
  135.     14. Floating Point
  136.     15. Variable-Length Argument Lists
  137.     16. Strange Problems
  138.     17. Style
  139.     18. Tools and Resources
  140.     19. System Dependencies
  141.     20. Miscellaneous
  142.  
  143. (The question numbers within each section are not continuous because
  144. they are aligned with the forthcoming book-length version, which
  145. contains even more questions.)
  146.  
  147. Herewith, some frequently-asked questions and their answers:
  148.  
  149.  
  150. Section 1. Declarations and Initializations
  151.  
  152. 1.1:    How do you decide which integer type to use?
  153.  
  154. A:    If you might need large values (above 32,767 or below -32,767),
  155.     use long.  Otherwise, if space is very important (i.e. if there
  156.     are large arrays or many structures), use short.  Otherwise, use
  157.     int.  If well-defined overflow characteristics are important and
  158.     negative values are not, or if you want to steer clear of sign-
  159.     extension problems when manipulating bits or bytes, use one of
  160.     the corresponding unsigned types.  (Beware when mixing signed
  161.     and unsigned values in expressions, though.)
  162.  
  163.     Although character types (especially unsigned char) can be used
  164.     as "tiny" integers, doing so is sometimes more trouble than it's
  165.     worth, due to unpredictable sign extension and increased code
  166.     size.  (Using unsigned char can help; see question 12.1 for a
  167.     related problem.)
  168.  
  169.     A similar space/time tradeoff applies when deciding between
  170.     float and double.  None of the above rules apply if the address
  171.     of a variable is taken and must have a particular type.
  172.  
  173.     If for some reason you need to declare something with an *exact*
  174.     size (usually the only good reason for doing so is when
  175.     attempting to conform to some externally-imposed storage layout,
  176.     but see question 20.5), be sure to encapsulate the choice behind
  177.     an appropriate typedef.
  178.  
  179.     References: K&R1 Sec. 2.2 p. 34; K&R2 Sec. 2.2 p. 36, Sec. A4.2
  180.     pp. 195-6, Sec. B11 p. 257; ANSI Sec. 2.2.4.2.1, Sec. 3.1.2.5;
  181.     ISO Sec. 5.2.4.2.1, Sec. 6.1.2.5; H&S Secs. 5.1,5.2 pp. 110-114.
  182.  
  183. 1.4:    What should the 64-bit type on new, 64-bit machines be?
  184.  
  185. A:    Some vendors of C products for 64-bit machines support 64-bit
  186.     long ints.  Others fear that too much existing code is written
  187.     to assume that ints and longs are the same size, or that one or
  188.     the other of them is exactly 32 bits, and introduce a new,
  189.     nonstandard, 64-bit long long (or __longlong) type instead.
  190.  
  191.     Programmers interested in writing portable code should therefore
  192.     insulate their 64-bit type needs behind appropriate typedefs.
  193.     Vendors who feel compelled to introduce a new, longer integral
  194.     type should advertise it as being "at least 64 bits" (which is
  195.     truly new, a type traditional C does not have), and not "exactly
  196.     64 bits."
  197.  
  198.     References: ANSI Sec. F.5.6; ISO Sec. G.5.6.
  199.  
  200. 1.7:    What's the best way to declare and define global variables?
  201.  
  202. A:    First, though there can be many "declarations" (and in many
  203.     translation units) of a single "global" (strictly speaking,
  204.     "external") variable or function, there must be exactly one
  205.     "definition".  (The definition is the declaration that actually
  206.     allocates space, and provides an initialization value, if any.)
  207.     The best arrangement is to place each definition in some
  208.     relevant .c file, with an external declaration in a header
  209.     (".h") file, which is #included wherever the declaration is
  210.     needed.  The .c file containing the definition should also
  211.     #include the same header file, so that the compiler can check
  212.     that the definition matches the declarations.
  213.  
  214.     This rule promotes a high degree of portability: it is
  215.     consistent with the requirements of the ANSI C Standard, and is
  216.     also consistent with most pre-ANSI compilers and linkers.  (Unix
  217.     compilers and linkers typically use a "common model" which
  218.     allows multiple definitions, as long as at most one is
  219.     initialized; this behavior is mentioned as a "common extension"
  220.     by the ANSI Standard, no pun intended.  A few very odd systems
  221.     may require an explicit initializer to distinguish a definition
  222.     from an external declaration.)
  223.  
  224.     It is possible to use preprocessor tricks to arrange that a line
  225.     like
  226.  
  227.         DEFINE(int, i);
  228.  
  229.     need only be entered once in one header file, and turned into a
  230.     definition or a declaration depending on the setting of some
  231.     macro, but it's not clear if this is worth the trouble.
  232.  
  233.     It's especially important to put global declarations in header
  234.     files if you want the compiler to catch inconsistent
  235.     declarations for you.  In particular, never place a prototype
  236.     for an external function in a .c file: it wouldn't generally be
  237.     checked for consistency with the definition, and an incompatible
  238.     prototype is worse than useless.
  239.  
  240.     See also questions 10.6 and 18.8.
  241.  
  242.     References: K&R1 Sec. 4.5 pp. 76-7; K&R2 Sec. 4.4 pp. 80-1; ANSI
  243.     Sec. 3.1.2.2, Sec. 3.7, Sec. 3.7.2, Sec. F.5.11; ISO
  244.     Sec. 6.1.2.2, Sec. 6.7, Sec. 6.7.2, Sec. G.5.11; Rationale
  245.     Sec. 3.1.2.2; H&S Sec. 4.8 pp. 101-104, Sec. 9.2.3 p. 267; CT&P
  246.     Sec. 4.2 pp. 54-56.
  247.  
  248. 1.11:    What does extern mean in a function declaration?
  249.  
  250. A:    It can be used as a stylistic hint to indicate that the
  251.     function's definition is probably in another source file, but
  252.     there is no formal difference between
  253.  
  254.         extern int f();
  255.  
  256.     and
  257.  
  258.         int f();
  259.  
  260.     References: ANSI Sec. 3.1.2.2, Sec. 3.5.1; ISO Sec. 6.1.2.2,
  261.     Sec. 6.5.1; Rationale Sec. 3.1.2.2; H&S Secs. 4.3,4.3.1 pp. 75-
  262.     6.
  263.  
  264. 1.12:    What's the auto keyword good for?
  265.  
  266. A:    Nothing; it's archaic.  See also question 20.37.
  267.  
  268.     References: K&R1 Sec. A8.1 p. 193; ANSI Sec. 3.1.2.4,
  269.     Sec. 3.5.1; ISO Sec. 6.1.2.4, Sec. 6.5.1; H&S Sec. 4.3 p. 75,
  270.     Sec. 4.3.1 p. 76.
  271.  
  272. 1.14:    I can't seem to define a linked list successfully.  I tried
  273.  
  274.         typedef struct {
  275.             char *item;
  276.             NODEPTR next;
  277.         } *NODEPTR;
  278.  
  279.     but the compiler gave me error messages.  Can't a structure in C
  280.     contain a pointer to itself?
  281.  
  282. A:    Structures in C can certainly contain pointers to themselves;
  283.     the discussion and example in section 6.5 of K&R make this
  284.     clear.  The problem with the NODEPTR example is that the typedef
  285.     has not been defined at the point where the "next" field is
  286.     declared.  To fix this code, first give the structure a tag
  287.     ("struct node").  Then, declare the "next" field as a simple
  288.     "struct node *", or disentangle the typedef declaration from the
  289.     structure definition, or both.  One corrected version would be
  290.  
  291.         struct node {
  292.             char *item;
  293.             struct node *next;
  294.         };
  295.  
  296.         typedef struct node *NODEPTR;
  297.  
  298.     and there are at least three other equivalently correct ways of
  299.     arranging it.
  300.  
  301.     A similar problem, with a similar solution, can arise when
  302.     attempting to declare a pair of typedef'ed mutually referential
  303.     structures.
  304.  
  305.     See also question 2.1.
  306.  
  307.     References: K&R1 Sec. 6.5 p. 101; K&R2 Sec. 6.5 p. 139; ANSI
  308.     Sec. 3.5.2, Sec. 3.5.2.3, esp. examples; ISO Sec. 6.5.2,
  309.     Sec. 6.5.2.3; H&S Sec. 5.6.1 pp. 132-3.
  310.  
  311. 1.21:    How do I declare an array of N pointers to functions returning
  312.     pointers to functions returning pointers to characters?
  313.  
  314. A:    The first part of this question can be answered in at least
  315.     three ways:
  316.  
  317.     1.  char *(*(*a[N])())();
  318.  
  319.     2.  Build the declaration up incrementally, using typedefs:
  320.  
  321.         typedef char *pc;    /* pointer to char */
  322.         typedef pc fpc();    /* function returning pointer to char */
  323.         typedef fpc *pfpc;    /* pointer to above */
  324.         typedef pfpc fpfpc();    /* function returning... */
  325.         typedef fpfpc *pfpfpc;    /* pointer to... */
  326.         pfpfpc a[N];        /* array of... */
  327.  
  328.     3.  Use the cdecl program, which turns English into C and vice
  329.         versa:
  330.  
  331.         cdecl> declare a as array of pointer to function returning
  332.             pointer to function returning pointer to char
  333.         char *(*(*a[])())()
  334.  
  335.         cdecl can also explain complicated declarations, help with
  336.         casts, and indicate which set of parentheses the arguments
  337.         go in (for complicated function definitions, like the one
  338.         above).  Versions of cdecl are in volume 14 of
  339.         comp.sources.unix (see question 18.16) and K&R2.
  340.  
  341.     Any good book on C should explain how to read these complicated
  342.     C declarations "inside out" to understand them ("declaration
  343.     mimics use").
  344.  
  345.     The pointer-to-function declarations in the examples above have
  346.     not included parameter type information.  When the parameters
  347.     have complicated types, declarations can *really* get messy.
  348.     (Modern versions of cdecl can help here, too.)
  349.  
  350.     References: K&R2 Sec. 5.12 p. 122; ANSI Sec. 3.5ff (esp.
  351.     Sec. 3.5.4); ISO Sec. 6.5ff (esp. Sec. 6.5.4); H&S Sec. 4.5 pp.
  352.     85-92, Sec. 5.10.1 pp. 149-50.
  353.  
  354. 1.22:    How can I declare a function that can return a pointer to a
  355.     function of the same type?  I'm building a state machine with
  356.     one function for each state, each of which returns a pointer to
  357.     the function for the next state.  But I can't find a way to
  358.     declare the functions.
  359.  
  360. A:    You can't quite do it directly.  Either have the function return
  361.     a generic function pointer, with some judicious casts to adjust
  362.     the types as the pointers are passed around; or have it return a
  363.     structure containing only a pointer to a function returning that
  364.     structure.
  365.  
  366. 1.25:    My compiler is complaining about an invalid redeclaration of a
  367.     function, but I only define it once and call it once.
  368.  
  369. A:    Functions which are called without a declaration in scope
  370.     (perhaps because the first call precedes the function's
  371.     definition) are assumed to be declared as returning int (and
  372.     without any argument type information), leading to discrepancies
  373.     if the function is later declared or defined otherwise.  Non-int
  374.     functions must be declared before they are called.
  375.  
  376.     Another possible source of this problem is that the function has
  377.     the same name as another one declared in some header file.
  378.  
  379.     See also questions 11.3 and 15.1.
  380.  
  381.     References: K&R1 Sec. 4.2 p. 70; K&R2 Sec. 4.2 p. 72; ANSI
  382.     Sec. 3.3.2.2; ISO Sec. 6.3.2.2; H&S Sec. 4.7 p. 101.
  383.  
  384. 1.30:    What can I safely assume about the initial values of variables
  385.     which are not explicitly initialized?  If global variables start
  386.     out as "zero," is that good enough for null pointers and
  387.     floating-point zeroes?
  388.  
  389. A:    Variables with "static" duration (that is, those declared
  390.     outside of functions, and those declared with the storage class
  391.     static), are guaranteed initialized (just once, at program
  392.     startup) to zero, as if the programmer had typed "= 0".
  393.     Therefore, such variables are initialized to the null pointer
  394.     (of the correct type; see also section 5) if they are pointers,
  395.     and to 0.0 if they are floating-point.
  396.  
  397.     Variables with "automatic" duration (i.e. local variables
  398.     without the static storage class) start out containing garbage,
  399.     unless they are explicitly initialized.  (Nothing useful can be
  400.     predicted about the garbage.)
  401.  
  402.     Dynamically-allocated memory obtained with malloc() and
  403.     realloc() is also likely to contain garbage, and must be
  404.     initialized by the calling program, as appropriate.  Memory
  405.     obtained with calloc() is all-bits-0, but this is not
  406.     necessarily useful for pointer or floating-point values (see
  407.     question 7.31, and section 5).
  408.  
  409.     References: K&R1 Sec. 4.9 pp. 82-4; K&R2 Sec. 4.9 pp. 85-86;
  410.     ANSI Sec. 3.5.7, Sec. 4.10.3.1, Sec. 4.10.5.3; ISO Sec. 6.5.7,
  411.     Sec. 7.10.3.1, Sec. 7.10.5.3; H&S Sec. 4.2.8 pp. 72-3, Sec. 4.6
  412.     pp. 92-3, Sec. 4.6.2 pp. 94-5, Sec. 4.6.3 p. 96, Sec. 16.1 p.
  413.     386.
  414.  
  415. 1.31:    This code, straight out of a book, isn't compiling:
  416.  
  417.         f()
  418.         {
  419.             char a[] = "Hello, world!";
  420.         }
  421.  
  422. A:    Perhaps you have a pre-ANSI compiler, which doesn't allow
  423.     initialization of "automatic aggregates" (i.e. non-static local
  424.     arrays, structures, and unions).  As a workaround, you can make
  425.     the array global or static (if you won't need a fresh copy
  426.     during any subsequent calls), or replace it with a pointer (if
  427.     the array won't be written to).  (You can always initialize
  428.     local char * variables to point to string literals, but see
  429.     question 1.32 below.)  If neither of these conditions hold,
  430.     you'll have to initialize the array by hand with strcpy() when
  431.     f() is called.  See also question 11.29.
  432.  
  433. 1.32:    What is the difference between these initializations?
  434.  
  435.         char a[] = "string literal";
  436.         char *p  = "string literal";
  437.  
  438.     My program crashes if I try to assign a new value to p[i].
  439.  
  440. A:    A string literal can be used in two slightly different ways.  As
  441.     an array initializer (as in the declaration of char a[]), it
  442.     specifies the initial values of the characters in that array.
  443.     Anywhere else, it turns into an unnamed, static array of
  444.     characters, which may be stored in read-only memory, which is
  445.     why you can't safely modify it.  In an expression context, the
  446.     array is converted at once to a pointer, as usual (see section
  447.     6), so the second declaration initializes p to point to the
  448.     unnamed array's first element.
  449.  
  450.     (For compiling old code, some compilers have a switch
  451.     controlling whether strings are writable or not.)
  452.  
  453.     See also questions 1.31, 6.1, 6.2, and 6.8.
  454.  
  455.     References: K&R2 Sec. 5.5 p. 104; ANSI Sec. 3.1.4, Sec. 3.5.7;
  456.     ISO Sec. 6.1.4, Sec. 6.5.7; Rationale Sec. 3.1.4; H&S Sec. 2.7.4
  457.     pp. 31-2.
  458.  
  459. 1.34:    I finally figured out the syntax for declaring pointers to
  460.     functions, but now how do I initialize one?
  461.  
  462. A:    Use something like
  463.  
  464.         extern int func();
  465.         int (*fp)() = func;
  466.  
  467.     When the name of a function appears in an expression like this,
  468.     it "decays" into a pointer (that is, it has its address
  469.     implicitly taken), much as an array name does.
  470.  
  471.     An explicit declaration for the function is normally needed,
  472.     since implicit external function declaration does not happen in
  473.     this case (because the function name in the initialization is
  474.     not part of a function call).
  475.  
  476.     See also question 4.12.
  477.  
  478.  
  479. Section 2. Structures, Unions, and Enumerations
  480.  
  481. 2.1:    What's the difference between these two declarations?
  482.  
  483.         struct x1 { ... };
  484.         typedef struct { ... } x2;
  485.  
  486. A:    The first form declares a "structure tag"; the second declares a
  487.     "typedef".  The main difference is that the second declaration
  488.     is of a slightly more abstract type -- its users don't
  489.     necessarily know that it is a structure, and the keyword struct
  490.     is not used when declaring instances of it.
  491.  
  492. 2.2:    Why doesn't
  493.  
  494.         struct x { ... };
  495.         x thestruct;
  496.  
  497.     work?
  498.  
  499. A:    C is not C++.  Typedef names are not automatically generated for
  500.     structure tags.  See also question 2.1 above.
  501.  
  502. 2.3:    Can a structure contain a pointer to itself?
  503.  
  504. A:    Most certainly.  See question 1.14.
  505.  
  506. 2.4:    What's the best way of implementing opaque (abstract) data types
  507.     in C?
  508.  
  509. A:    One good way is for clients to use structure pointers (perhaps
  510.     additionally hidden behind typedefs) which point to structure
  511.     types which are not publicly defined.
  512.  
  513. 2.6:    I came across some code that declared a structure like this:
  514.  
  515.         struct name {
  516.             int namelen;
  517.             char namestr[1];
  518.         };
  519.  
  520.     and then did some tricky allocation to make the namestr array
  521.     act like it had several elements.  Is this legal or portable?
  522.  
  523. A:    This technique is popular, although Dennis Ritchie has called it
  524.     "unwarranted chumminess with the C implementation."  An official
  525.     interpretation has deemed that it is not strictly conforming
  526.     with the C Standard.  (A thorough treatment of the arguments
  527.     surrounding the legality of the technique is beyond the scope of
  528.     this list.)  It does seem to be portable to all known
  529.     implementations.  (Compilers which check array bounds carefully
  530.     might issue warnings.)
  531.  
  532.     Another possibility is to declare the variable-size element very
  533.     large, rather than very small; in the case of the above example:
  534.  
  535.         ...
  536.         char namestr[MAXSIZE];
  537.         ...
  538.  
  539.     where MAXSIZE is larger than any name which will be stored.
  540.     However, it looks like this technique is disallowed by a strict
  541.     interpretation of the Standard as well.
  542.  
  543.     References: Rationale Sec. 3.5.4.2.
  544.  
  545. 2.7:    I heard that structures could be assigned to variables and
  546.     passed to and from functions, but K&R1 says not.
  547.  
  548. A:    What K&R1 said was that the restrictions on structure operations
  549.     would be lifted in a forthcoming version of the compiler, and in
  550.     fact structure assignment and passing were fully functional in
  551.     Ritchie's compiler even as K&R1 was being published.  Although a
  552.     few early C compilers lacked these operations, all modern
  553.     compilers support them, and they are part of the ANSI C
  554.     standard, so there should be no reluctance to use them.
  555.  
  556.     (Note that when a structure is assigned, passed, or returned,
  557.     the copying is done monolithically; anything pointed to by any
  558.     pointer fields is *not* copied.)
  559.  
  560.     References: K&R1 Sec. 6.2 p. 121; K&R2 Sec. 6.2 p. 129; ANSI
  561.     Sec. 3.1.2.5, Sec. 3.2.2.1, Sec. 3.3.16; ISO Sec. 6.1.2.5,
  562.     Sec. 6.2.2.1, Sec. 6.3.16; H&S Sec. 5.6.2 p. 133.
  563.  
  564. 2.8:    Why can't you compare structures?
  565.  
  566. A:    There is no single, good way for a compiler to implement
  567.     structure comparison which is consistent with C's low-level
  568.     flavor.  A simple byte-by-byte comparison could founder on
  569.     random bits present in unused "holes" in the structure (such
  570.     padding is used to keep the alignment of later fields correct;
  571.     see question 2.12).  A field-by-field comparison might require
  572.     unacceptable amounts of repetitive code for large structures.
  573.  
  574.     If you need to compare two structures, you'll have to write your
  575.     own function to do so, field by field.
  576.  
  577.     References: K&R2 Sec. 6.2 p. 129; ANSI Sec. 4.11.4.1 footnote
  578.     136; Rationale Sec. 3.3.9; H&S Sec. 5.6.2 p. 133.
  579.  
  580. 2.9:    How are structure passing and returning implemented?
  581.  
  582. A:    When structures are passed as arguments to functions, the entire
  583.     structure is typically pushed on the stack, using as many words
  584.     as are required.  (Programmers often choose to use pointers to
  585.     structures instead, precisely to avoid this overhead.)  Some
  586.     compilers merely pass a pointer to the structure, though they
  587.     may have to make a local copy to preserve pass-by-value
  588.     semantics.
  589.  
  590.     Structures are often returned from functions in a location
  591.     pointed to by an extra, compiler-supplied "hidden" argument to
  592.     the function.  Some older compilers used a special, static
  593.     location for structure returns, although this made structure-
  594.     valued functions non-reentrant, which ANSI C disallows.
  595.  
  596.     References: ANSI Sec. 2.2.3; ISO Sec. 5.2.3.
  597.  
  598. 2.10:    How can I pass constant values to functions which accept
  599.     structure arguments?
  600.  
  601. A:    C has no way of generating anonymous structure values.  You will
  602.     have to use a temporary structure variable or a little structure-
  603.     building function.  (gcc provides structure constants as an
  604.     extension, and the mechanism will probably be added to a future
  605.     revision of the C Standard.)  See also question 4.10.
  606.  
  607. 2.11:    How can I read/write structures from/to data files?
  608.  
  609. A:    It is relatively straightforward to write a structure out using
  610.     fwrite():
  611.  
  612.         fwrite(&somestruct, sizeof somestruct, 1, fp);
  613.  
  614.     and a corresponding fread invocation can read it back in.
  615.     (Under pre-ANSI C, a (char *) cast on the first argument is
  616.     required.  What's important is that fwrite() receive a byte
  617.     pointer, not a structure pointer.)  However, data files so
  618.     written will *not* be portable (see questions 2.12 and 20.5).
  619.     Note also that if the structure contains any pointers, only the
  620.     pointer values will be written, and they are most unlikely to be
  621.     valid when read back in.  Finally, note that for widespread
  622.     portability you must use the "b" flag when fopening the files;
  623.     see question 12.38.
  624.  
  625.     A more portable solution, though it's a bit more work initially,
  626.     is to write a pair of functions for writing and reading a
  627.     structure, field-by-field, in a portable (perhaps even human-
  628.     readable) way.
  629.  
  630.     References: H&S Sec. 15.13 p. 381.
  631.  
  632. 2.12:    My compiler is leaving holes in structures, which is wasting
  633.     space and preventing "binary" I/O to external data files.  Can I
  634.     turn off the padding, or otherwise control the alignment of
  635.     structure fields?
  636.  
  637. A:    Your compiler may provide an extension to give you this control
  638.     (perhaps a #pragma; see question 11.20), but there is no
  639.     standard method.
  640.  
  641.     See also question 20.5.
  642.  
  643.     References: K&R2 Sec. 6.4 p. 138; H&S Sec. 5.6.4 p. 135.
  644.  
  645. 2.13:    Why does sizeof report a larger size than I expect for a
  646.     structure type, as if there were padding at the end?
  647.  
  648. A:    Structures may have this padding (as well as internal padding),
  649.     if necessary, to ensure that alignment properties will be
  650.     preserved when an array of contiguous structures is allocated.
  651.     Even when the structure is not part of an array, the end padding
  652.     remains, so that sizeof can always return a consistent size.
  653.     See question 2.12 above.
  654.  
  655.     References: H&S Sec. 5.6.7 pp. 139-40.
  656.  
  657. 2.14:    How can I determine the byte offset of a field within a
  658.     structure?
  659.  
  660. A:    ANSI C defines the offsetof() macro, which should be used if
  661.     available; see <stddef.h>.  If you don't have it, one possible
  662.     implementation is
  663.  
  664.         #define offsetof(type, mem) ((size_t) \
  665.             ((char *)&((type *)0)->mem - (char *)(type *)0))
  666.  
  667.     This implementation is not 100% portable; some compilers may
  668.     legitimately refuse to accept it.
  669.  
  670.     See question 2.15 below for a usage hint.
  671.  
  672.     References: ANSI Sec. 4.1.5; ISO Sec. 7.1.6; Rationale
  673.     Sec. 3.5.4.2; H&S Sec. 11.1 pp. 292-3.
  674.  
  675. 2.15:    How can I access structure fields by name at run time?
  676.  
  677. A:    Build a table of names and offsets, using the offsetof() macro.
  678.     The offset of field b in struct a is
  679.  
  680.         offsetb = offsetof(struct a, b)
  681.  
  682.     If structp is a pointer to an instance of this structure, and
  683.     field b is an int (with offset as computed above), b's value can
  684.     be set indirectly with
  685.  
  686.         *(int *)((char *)structp + offsetb) = value;
  687.  
  688. 2.18:    This program works correctly, but it dumps core after it
  689.     finishes.  Why?
  690.  
  691.         struct list {
  692.             char *item;
  693.             struct list *next;
  694.         }
  695.  
  696.         /* Here is the main program. */
  697.  
  698.         main(argc, argv)
  699.         { ... }
  700.  
  701. A:    A missing semicolon causes main() to be declared as returning a
  702.     structure.  (The connection is hard to see because of the
  703.     intervening comment.)  Since structure-valued functions are
  704.     usually implemented by adding a hidden return pointer (see
  705.     question 2.9), the generated code for main() tries to accept
  706.     three arguments, although only two are passed (in this case, by
  707.     the C start-up code).  See also questions 10.9 and 16.4.
  708.  
  709.     References: CT&P Sec. 2.3 pp. 21-2.
  710.  
  711. 2.20:    Can I initialize unions?
  712.  
  713. A:    ANSI Standard C allows an initializer for the first member of a
  714.     union.  There is no standard way of initializing any other
  715.     member (nor, under a pre-ANSI compiler, is there generally any
  716.     way of initializing a union at all).
  717.  
  718.     References: K&R2 Sec. 6.8 pp. 148-9; ANSI Sec. 3.5.7; ISO
  719.     Sec. 6.5.7; H&S Sec. 4.6.7 p. 100.
  720.  
  721. 2.22:    What is the difference between an enumeration and a set of
  722.     preprocessor #defines?
  723.  
  724. A:    At the present time, there is little difference.  Although many
  725.     people might have wished otherwise, the C Standard says that
  726.     enumerations may be freely intermixed with other integral types,
  727.     without errors.  (If such intermixing were disallowed without
  728.     explicit casts, judicious use of enumerations could catch
  729.     certain programming errors.)
  730.  
  731.     Some advantages of enumerations are that the numeric values are
  732.     automatically assigned, that a debugger may be able to display
  733.     the symbolic values when enumeration variables are examined, and
  734.     that they obey block scope.  (A compiler may also generate
  735.     nonfatal warnings when enumerations and integers are
  736.     indiscriminately mixed, since doing so can still be considered
  737.     bad style even though it is not strictly illegal.)  A
  738.     disadvantage is that the programmer has little control over
  739.     those nonfatal warnings; some programmers also resent not having
  740.     control over the sizes of enumeration variables.
  741.  
  742.     References: K&R2 Sec. 2.3 p. 39, Sec. A4.2 p. 196; ANSI
  743.     Sec. 3.1.2.5, Sec. 3.5.2, Sec. 3.5.2.2, Appendix E; ISO
  744.     Sec. 6.1.2.5, Sec. 6.5.2, Sec. 6.5.2.2, Annex F; H&S Sec. 5.5
  745.     pp. 127-9, Sec. 5.11.2 p. 153.
  746.  
  747. 2.24:    Is there an easy way to print enumeration values symbolically?
  748.  
  749. A:    No.  You can write a little function to map an enumeration
  750.     constant to a string.  (If all you're worried about is
  751.     debugging, a good debugger should automatically print
  752.     enumeration constants symbolically.)
  753.  
  754.  
  755. Section 3. Expressions
  756.  
  757. 3.1:    Why doesn't this code:
  758.  
  759.         a[i] = i++;
  760.  
  761.     work?
  762.  
  763. A:    The subexpression i++ causes a side effect -- it modifies i's
  764.     value -- which leads to undefined behavior since i is also
  765.     referenced elsewhere in the same expression.  (Note that
  766.     although the language in K&R suggests that the behavior of this
  767.     expression is unspecified, the C Standard makes the stronger
  768.     statement that it is undefined -- see question 11.33.)
  769.  
  770.     References: K&R1 Sec. 2.12; K&R2 Sec. 2.12; ANSI Sec. 3.3; ISO
  771.     Sec. 6.3.
  772.  
  773. 3.2:    Under my compiler, the code
  774.  
  775.         int i = 7;
  776.         printf("%d\n", i++ * i++);
  777.  
  778.     prints 49.  Regardless of the order of evaluation, shouldn't it
  779.     print 56?
  780.  
  781. A:    Although the postincrement and postdecrement operators ++ and --
  782.     perform their operations after yielding the former value, the
  783.     implication of "after" is often misunderstood.  It is *not*
  784.     guaranteed that an increment or decrement is performed
  785.     immediately after giving up the previous value and before any
  786.     other part of the expression is evaluated.  It is merely
  787.     guaranteed that the update will be performed sometime before the
  788.     expression is considered "finished" (before the next "sequence
  789.     point," in ANSI C's terminology; see question 3.8).  In the
  790.     example, the compiler chose to multiply the previous value by
  791.     itself and to perform both increments afterwards.
  792.  
  793.     The behavior of code which contains multiple, ambiguous side
  794.     effects has always been undefined.  (Loosely speaking, by
  795.     "multiple, ambiguous side effects" we mean any combination of
  796.     ++, --, =, +=, -=, etc. in a single expression which causes the
  797.     same object either to be modified twice or modified and then
  798.     inspected.  This is a rough definition; see question 3.8 for a
  799.     precise one, and question 11.33 for the meaning of "undefined.")
  800.     Don't even try to find out how your compiler implements such
  801.     things (contrary to the ill-advised exercises in many C
  802.     textbooks); as K&R wisely point out, "if you don't know *how*
  803.     they are done on various machines, that innocence may help to
  804.     protect you."
  805.  
  806.     References: K&R1 Sec. 2.12 p. 50; K&R2 Sec. 2.12 p. 54; ANSI
  807.     Sec. 3.3; ISO Sec. 6.3; CT&P Sec. 3.7 p. 47; PCS Sec. 9.5 pp.
  808.     120-1.
  809.  
  810. 3.3:    I've experimented with the code
  811.  
  812.         int i = 3;
  813.         i = i++;
  814.  
  815.     on several compilers.  Some gave i the value 3, some gave 4, but
  816.     one gave 7.  I know the behavior is undefined, but how could it
  817.     give 7?
  818.  
  819. A:    Undefined behavior means *anything* can happen.  See questions
  820.     3.9 and 11.33.  (Also, note that neither i++ nor ++i is the same
  821.     as i+1.  If you want to increment i, use i=i+1 or i++ or ++i,
  822.     not some combination.  See also question 3.12.)
  823.  
  824. 3.4:    Can I use explicit parentheses to force the order of evaluation
  825.     I want?  Even if I don't, doesn't precedence dictate it?
  826.  
  827. A:    Not in general.
  828.  
  829.     Operator precedence and explicit parentheses impose only a
  830.     partial ordering on the evaluation of an expression.  In the
  831.     expression
  832.  
  833.         f() + g() * h()
  834.  
  835.     although we know that the multiplication will happen before the
  836.     addition, there is no telling which of the three functions will
  837.     be called first.
  838.  
  839.     When you need to ensure the order of subexpression evaluation,
  840.     you may need to use explicit temporary variables and separate
  841.     statements.
  842.  
  843.     References: K&R1 Sec. 2.12 p. 49, Sec. A.7 p. 185; K&R2
  844.     Sec. 2.12 pp. 52-3, Sec. A.7 p. 200.
  845.  
  846. 3.5:    But what about the && and || operators?
  847.     I see code like "while((c = getchar()) != EOF && c != '\n')" ...
  848.  
  849. A:    There is a special exception for those operators (as well as the
  850.     ?: operator): left-to-right evaluation is guaranteed (as is an
  851.     intermediate sequence point, see question 3.8).  Any book on C
  852.     should make this clear.
  853.  
  854.     References: K&R1 Sec. 2.6 p. 38, Secs. A7.11-12 pp. 190-1; K&R2
  855.     Sec. 2.6 p. 41, Secs. A7.14-15 pp. 207-8; ANSI Sec. 3.3.13,
  856.     Sec. 3.3.14, Sec. 3.3.15; ISO Sec. 6.3.13, Sec. 6.3.14,
  857.     Sec. 6.3.15; H&S Sec. 7.7 pp. 217-8, Sec. 7.8 pp. 218-20,
  858.     Sec. 7.12.1 p. 229; CT&P Sec. 3.7 pp. 46-7.
  859.  
  860. 3.8:    How can I understand these complex expressions?  What's a
  861.     "sequence point"?
  862.  
  863. A:    A sequence point is the point (at the end of a full expression,
  864.     or at the ||, &&, ?:, or comma operators, or just before a
  865.     function call) at which the dust has settled and all side
  866.     effects are guaranteed to be complete.  The ANSI/ISO C Standard
  867.     states that
  868.  
  869.         Between the previous and next sequence point an
  870.         object shall have its stored value modified at
  871.         most once by the evaluation of an expression.
  872.         Furthermore, the prior value shall be accessed
  873.         only to determine the value to be stored.
  874.  
  875.     The second sentence can be difficult to understand.  It says
  876.     that if an object is written to within a full expression, any
  877.     and all accesses to it within the same expression must be for
  878.     the purposes of computing the value to be written.  This rule
  879.     effectively constrains legal expressions to those in which the
  880.     accesses demonstrably precede the modification.
  881.  
  882.     See also question 3.9 below.
  883.  
  884.     References: ANSI Sec. 2.1.2.3, Sec. 3.3, Appendix B; ISO
  885.     Sec. 5.1.2.3, Sec. 6.3, Annex C; Rationale Sec. 2.1.2.3; H&S
  886.     Sec. 7.12.1 pp. 228-9.
  887.  
  888. 3.9:    So given
  889.  
  890.         a[i] = i++;
  891.  
  892.     we don't know which cell of a[] gets written to, but i does get
  893.     incremented by one.
  894.  
  895. A:    *No.*  Once an expression or program becomes undefined, *all*
  896.     aspects of it become undefined.  See questions 3.2, 3.3, 11.33,
  897.     and 11.35.
  898.  
  899. 3.12:    If I'm not using the value of the expression, should I use i++
  900.     or ++i to increment a variable?
  901.  
  902. A:    Since the two forms differ only in the value yielded, they are
  903.     entirely equivalent when only their side effect is needed.
  904.  
  905.     See also question 3.3.
  906.  
  907.     References: K&R1 Sec. 2.8 p. 43; K&R2 Sec. 2.8 p. 47; ANSI
  908.     Sec. 3.3.2.4, Sec. 3.3.3.1; ISO Sec. 6.3.2.4, Sec. 6.3.3.1; H&S
  909.     Sec. 7.4.4 pp. 192-3, Sec. 7.5.8 pp. 199-200.
  910.  
  911.  
  912. 3.14:    Why doesn't the code
  913.  
  914.         int a = 1000, b = 1000;
  915.         long int c = a * b;
  916.  
  917.     work?
  918.  
  919. A:    Under C's integral promotion rules, the multiplication is
  920.     carried out using int arithmetic, and the result may overflow or
  921.     be truncated before being promoted and assigned to the long int
  922.     left-hand side.  Use an explicit cast to force long arithmetic:
  923.  
  924.         long int c = (long int)a * b;
  925.  
  926.     Note that (long int)(a * b) would *not* have the desired effect.
  927.  
  928.     A similar problem can arise when two integers are divided, with
  929.     the result assigned to a floating-point variable.
  930.  
  931.     References: K&R1 Sec. 2.7 p. 41; K&R2 Sec. 2.7 p. 44; ANSI
  932.     Sec. 3.2.1.5; ISO Sec. 6.2.1.5; H&S Sec. 6.3.4 p. 176; CT&P
  933.     Sec. 3.9 pp. 49-50.
  934.  
  935. 3.16:    I have a complicated expression which I have to assign to one of
  936.     two variables, depending on a condition.  Can I use code like
  937.     this?
  938.  
  939.         ((condition) ? a : b) = complicated_expression;
  940.  
  941. A:    No.  The ?: operator, like most operators, yields a value, and
  942.     you can't assign to a value.  (In other words, ?: does not yield
  943.     an "lvalue".)  If you really want to, you can try something like
  944.  
  945.         *((condition) ? &a : &b) = complicated_expression;
  946.  
  947.     although this is admittedly not as pretty.
  948.  
  949.     References: ANSI Sec. 3.3.15 esp. footnote 50; ISO Sec. 6.3.15;
  950.     H&S Sec. 7.1 pp. 179-180.
  951.  
  952.  
  953. Section 4. Pointers
  954.  
  955. 4.2:    I'm trying to declare a pointer and allocate some space for it,
  956.     but it's not working.  What's wrong with this code?
  957.  
  958.         char *p;
  959.         *p = malloc(10);
  960.  
  961. A:    The pointer you declared is p, not *p.  To make a pointer point
  962.     somewhere, you just use the name of the pointer:
  963.  
  964.         p = malloc(10);
  965.  
  966.     It's when you're manipulating the pointed-to memory that you use
  967.     * as an indirection operator:
  968.  
  969.         *p = 'H';
  970.  
  971.     See also questions 1.21, 7.1, and 8.3.
  972.  
  973.     References: CT&P Sec. 3.1 p. 28.
  974.  
  975. 4.3:    Does *p++ increment p, or what it points to?
  976.  
  977. A:    Unary operators like *, ++, and -- all associate (group) from
  978.     right to left.  Therefore, *p++ increments p (and returns the
  979.     value pointed to by p before the increment).  To increment the
  980.     value pointed to by p, use (*p)++ (or perhaps ++*p, if the order
  981.     of the side effect doesn't matter).
  982.  
  983.     References: K&R1 Sec. 5.1 p. 91; K&R2 Sec. 5.1 p. 95; ANSI
  984.     Sec. 3.3.2, Sec. 3.3.3; ISO Sec. 6.3.2, Sec. 6.3.3; H&S
  985.     Sec. 7.4.4 pp. 192-3, Sec. 7.5 p. 193, Secs. 7.5.7,7.5.8 pp. 199-
  986.     200.
  987.  
  988. 4.5:    I have a char * pointer that happens to point to some ints, and
  989.     I want to step it over them.  Why doesn't
  990.  
  991.         ((int *)p)++;
  992.  
  993.     work?
  994.  
  995. A:    In C, a cast operator does not mean "pretend these bits have a
  996.     different type, and treat them accordingly"; it is a conversion
  997.     operator, and by definition it yields an rvalue, which cannot be
  998.     assigned to, or incremented with ++.  (It is an anomaly in pcc-
  999.     derived compilers, and an extension in gcc, that expressions
  1000.     such as the above are ever accepted.)  Say what you mean: use
  1001.  
  1002.         p = (char *)((int *)p + 1);
  1003.  
  1004.     or (since p is a char *) simply
  1005.  
  1006.         p += sizeof(int);
  1007.  
  1008.     Whenever possible, you should choose appropriate pointer types
  1009.     in the first place, instead of trying to treat one type as
  1010.     another.
  1011.  
  1012.     References: K&R2 Sec. A7.5 p. 205; ANSI Sec. 3.3.4 (esp.
  1013.     footnote 14); ISO Sec. 6.3.4; Rationale Sec. 3.3.2.4; H&S
  1014.     Sec. 7.1 pp. 179-80.
  1015.  
  1016. 4.8:    I have a function which accepts, and is supposed to initialize,
  1017.     a pointer:
  1018.  
  1019.         void f(ip)
  1020.         int *ip;
  1021.         {
  1022.             static int dummy = 5;
  1023.             ip = &dummy;
  1024.         }
  1025.  
  1026.     But when I call it like this:
  1027.  
  1028.         int *ip;
  1029.         f(ip);
  1030.  
  1031.     the pointer in the caller remains unchanged.
  1032.  
  1033. A:    Are you sure the function initialized what you thought it did?
  1034.     Remember that arguments in C are passed by value.  The called
  1035.     function altered only the passed copy of the pointer.  You'll
  1036.     either want to pass the address of the pointer (the function
  1037.     will end up accepting a pointer-to-a-pointer), or have the
  1038.     function return the pointer.
  1039.  
  1040.     See also questions 4.9 and 4.11.
  1041.  
  1042.  
  1043. 4.9:    Can I use a void ** pointer to pass a generic pointer to a
  1044.     function by reference?
  1045.  
  1046. A:    Not portably.  There is no generic pointer-to-pointer type in C.
  1047.     void * acts as a generic pointer only because conversions are
  1048.     applied automatically when other pointer types are assigned to
  1049.     and from void *'s; these conversions cannot be performed (the
  1050.     correct underlying pointer type is not known) if an attempt is
  1051.     made to indirect upon a void ** value which points at something
  1052.     other than a void *.
  1053.  
  1054. 4.10:    I have a function
  1055.  
  1056.         extern int f(int *);
  1057.  
  1058.     which accepts a pointer to an int.  How can I pass a constant by
  1059.     reference?  A call like
  1060.  
  1061.         f(&5);
  1062.  
  1063.     doesn't seem to work.
  1064.  
  1065. A:    You can't do this directly.  You will have to declare a
  1066.     temporary variable, and then pass its address to the function:
  1067.  
  1068.         int five = 5;
  1069.         f(&five);
  1070.  
  1071.     See also questions 2.10, 4.8, and 20.1.
  1072.  
  1073. 4.11:    Does C even have "pass by reference"?
  1074.  
  1075. A:    Not really.  Strictly speaking, C always uses pass by value.
  1076.     You can simulate pass by reference yourself, by defining
  1077.     functions which accept pointers and then using the & operator
  1078.     when calling, and the compiler will essentially simulate it for
  1079.     you when you pass an array to a function (by passing a pointer
  1080.     instead, see question 6.4 et al.), but C has nothing truly
  1081.     equivalent to formal pass by reference or C++ reference
  1082.     parameters.  (However, function-like preprocessor macros do
  1083.     provide a form of "call by name".)
  1084.  
  1085.     See also questions 4.8 and 20.1.
  1086.  
  1087.     References: K&R1 Sec. 1.8 pp. 24-5, Sec. 5.2 pp. 91-3; K&R2
  1088.     Sec. 1.8 pp. 27-8, Sec. 5.2 pp. 91-3; ANSI Sec. 3.3.2.2, esp.
  1089.     footnote 39; ISO Sec. 6.3.2.2; H&S Sec. 9.5 pp. 273-4.
  1090.  
  1091. 4.12:    I've seen different methods used for calling functions via
  1092.     pointers.  What's the story?
  1093.  
  1094. A:    Originally, a pointer to a function had to be "turned into" a
  1095.     "real" function, with the * operator (and an extra pair of
  1096.     parentheses, to keep the precedence straight), before calling:
  1097.  
  1098.         int r, func(), (*fp)() = func;
  1099.         r = (*fp)();
  1100.  
  1101.  
  1102.     It can also be argued that functions are always called via
  1103.     pointers, and that "real" function names always decay implicitly
  1104.     into pointers (in expressions, as they do in initializations;
  1105.     see question 1.34).  This reasoning, made widespread through pcc
  1106.     and adopted in the ANSI standard, means that
  1107.  
  1108.  
  1109.         r = fp();
  1110.  
  1111.     is legal and works correctly, whether fp is the name of a
  1112.     function or a pointer to one.  (The usage has always been
  1113.     unambiguous; there is nothing you ever could have done with a
  1114.     function pointer followed by an argument list except call the
  1115.     function pointed to.)  An explicit * is still allowed (and
  1116.     recommended, if portability to older compilers is important).
  1117.  
  1118.     See also question 1.34.
  1119.  
  1120.     References: K&R1 Sec. 5.12 p. 116; K&R2 Sec. 5.11 p. 120; ANSI
  1121.     Sec. 3.3.2.2; ISO Sec. 6.3.2.2; Rationale Sec. 3.3.2.2; H&S
  1122.     Sec. 5.8 p. 147, Sec. 7.4.3 p. 190.
  1123.  
  1124.  
  1125. Section 5. Null Pointers
  1126.  
  1127. 5.1:    What is this infamous null pointer, anyway?
  1128.  
  1129. A:    The language definition states that for each pointer type, there
  1130.     is a special value -- the "null pointer" -- which is
  1131.     distinguishable from all other pointer values and which is
  1132.     "guaranteed to compare unequal to a pointer to any object or
  1133.     function."  That is, the address-of operator & will never yield
  1134.     a null pointer, nor will a successful call to malloc().
  1135.     (malloc() does return a null pointer when it fails, and this is
  1136.     a typical use of null pointers: as a "special" pointer value
  1137.     with some other meaning, usually "not allocated" or "not
  1138.     pointing anywhere yet.")
  1139.  
  1140.     A null pointer is conceptually different from an uninitialized
  1141.     pointer.  A null pointer is known not to point to any object or
  1142.     function; an uninitialized pointer might point anywhere.  See
  1143.     also questions 1.30, 7.1, and 7.31.
  1144.  
  1145.     As mentioned above, there is a null pointer for each pointer
  1146.     type, and the internal values of null pointers for different
  1147.     types may be different.  Although programmers need not know the
  1148.     internal values, the compiler must always be informed which type
  1149.     of null pointer is required, so that it can make the distinction
  1150.     if necessary (see questions 5.2, 5.5, and 5.6 below).
  1151.  
  1152.     References: K&R1 Sec. 5.4 pp. 97-8; K&R2 Sec. 5.4 p. 102; ANSI
  1153.     Sec. 3.2.2.3; ISO Sec. 6.2.2.3; Rationale Sec. 3.2.2.3; H&S
  1154.     Sec. 5.3.2 pp. 121-3.
  1155.  
  1156. 5.2:    How do I get a null pointer in my programs?
  1157.  
  1158. A:    According to the language definition, a constant 0 in a pointer
  1159.     context is converted into a null pointer at compile time.  That
  1160.     is, in an initialization, assignment, or comparison when one
  1161.     side is a variable or expression of pointer type, the compiler
  1162.     can tell that a constant 0 on the other side requests a null
  1163.     pointer, and generate the correctly-typed null pointer value.
  1164.     Therefore, the following fragments are perfectly legal:
  1165.  
  1166.         char *p = 0;
  1167.         if(p != 0)
  1168.  
  1169.     (See also question 5.3.)
  1170.  
  1171.     However, an argument being passed to a function is not
  1172.     necessarily recognizable as a pointer context, and the compiler
  1173.     may not be able to tell that an unadorned 0 "means" a null
  1174.     pointer.  To generate a null pointer in a function call context,
  1175.     an explicit cast may be required, to force the 0 to be
  1176.     recognized as a pointer.  For example, the Unix system call
  1177.     execl takes a variable-length, null-pointer-terminated list of
  1178.     character pointer arguments, and is correctly called like this:
  1179.  
  1180.         execl("/bin/sh", "sh", "-c", "date", (char *)0);
  1181.  
  1182.     If the (char *) cast on the last argument were omitted, the
  1183.     compiler would not know to pass a null pointer, and would pass
  1184.     an integer 0 instead.  (Note that many Unix manuals get this
  1185.     example wrong .)
  1186.  
  1187.     When function prototypes are in scope, argument passing becomes
  1188.     an "assignment context," and most casts may safely be omitted,
  1189.     since the prototype tells the compiler that a pointer is
  1190.     required, and of which type, enabling it to correctly convert an
  1191.     unadorned 0.  Function prototypes cannot provide the types for
  1192.     variable arguments in variable-length argument lists however, so
  1193.     explicit casts are still required for those arguments.  (See
  1194.     also question 15.3.)  It is safest to properly cast all null
  1195.     pointer constants in function calls: to guard against varargs
  1196.     functions or those without prototypes, to allow interim use of
  1197.     non-ANSI compilers, and to demonstrate that you know what you
  1198.     are doing.  (Incidentally, it's also a simpler rule to
  1199.     remember.)
  1200.  
  1201.     Summary:
  1202.  
  1203.         Unadorned 0 okay:    Explicit cast required:
  1204.  
  1205.         initialization        function call,
  1206.                     no prototype in scope
  1207.         assignment
  1208.                     variable argument in
  1209.         comparison        varargs function call
  1210.  
  1211.         function call,
  1212.         prototype in scope,
  1213.         fixed argument
  1214.  
  1215.     References: K&R1 Sec. A7.7 p. 190, Sec. A7.14 p. 192; K&R2
  1216.     Sec. A7.10 p. 207, Sec. A7.17 p. 209; ANSI Sec. 3.2.2.3; ISO
  1217.     Sec. 6.2.2.3; H&S Sec. 4.6.3 p. 95, Sec. 6.2.7 p. 171.
  1218.  
  1219. 5.3:    Is the abbreviated pointer comparison "if(p)" to test for non-
  1220.     null pointers valid?  What if the internal representation for
  1221.     null pointers is nonzero?
  1222.  
  1223. A:    When C requires the Boolean value of an expression (in the if,
  1224.     while, for, and do statements, and with the &&, ||, !, and ?:
  1225.     operators), a false value is inferred when the expression
  1226.     compares equal to zero, and a true value otherwise.  That is,
  1227.     whenever one writes
  1228.  
  1229.         if(expr)
  1230.  
  1231.     where "expr" is any expression at all, the compiler essentially
  1232.     acts as if it had been written as
  1233.  
  1234.         if((expr) != 0)
  1235.  
  1236.     Substituting the trivial pointer expression "p" for "expr," we
  1237.     have
  1238.  
  1239.         if(p)    is equivalent to        if(p != 0)
  1240.  
  1241.     and this is a comparison context, so the compiler can tell that
  1242.     the (implicit) 0 is actually a null pointer constant, and use
  1243.     the correct null pointer value.  There is no trickery involved
  1244.     here; compilers do work this way, and generate identical code
  1245.     for both constructs.  The internal representation of a null
  1246.     pointer does *not* matter.
  1247.  
  1248.     The boolean negation operator, !, can be described as follows:
  1249.  
  1250.         !expr    is essentially equivalent to    (expr)?0:1
  1251.             or to                ((expr) == 0)
  1252.  
  1253.     which leads to the conclusion that
  1254.  
  1255.         if(!p)    is equivalent to        if(p == 0)
  1256.  
  1257.     "Abbreviations" such as if(p), though perfectly legal, are
  1258.     considered by some to be bad style (and by others to be good
  1259.     style; see question 17.10).
  1260.  
  1261.     See also question 9.2.
  1262.  
  1263.     References: K&R2 Sec. A7.4.7 p. 204; ANSI Sec. 3.3.3.3,
  1264.     Sec. 3.3.9, Sec. 3.3.13, Sec. 3.3.14, Sec. 3.3.15, Sec. 3.6.4.1,
  1265.     Sec. 3.6.5; ISO Sec. 6.3.3.3, Sec. 6.3.9, Sec. 6.3.13,
  1266.     Sec. 6.3.14, Sec. 6.3.15, Sec. 6.6.4.1, Sec. 6.6.5; H&S
  1267.     Sec. 5.3.2 p. 122.
  1268.  
  1269. 5.4:    What is NULL and how is it #defined?
  1270.  
  1271. A:    As a matter of style, many programmers prefer not to have
  1272.     unadorned 0's scattered through their programs.  Therefore, the
  1273.     preprocessor macro NULL is #defined (by <stdio.h> or <stddef.h>)
  1274.     with the value 0, possibly cast to (void *) (see also question
  1275.     5.6).  A programmer who wishes to make explicit the distinction
  1276.     between 0 the integer and 0 the null pointer constant can then
  1277.     use NULL whenever a null pointer is required.
  1278.  
  1279.     Using NULL is a stylistic convention only; the preprocessor
  1280.     turns NULL back into 0 which is then recognized by the compiler,
  1281.     in pointer contexts, as before.  In particular, a cast may still
  1282.     be necessary before NULL (as before 0) in a function call
  1283.     argument.  The table under question 5.2 above applies for NULL
  1284.     as well as 0 (an unadorned NULL is equivalent to an unadorned
  1285.     0).
  1286.  
  1287.     NULL should *only* be used for pointers; see question 5.9.
  1288.  
  1289.     References: K&R1 Sec. 5.4 pp. 97-8; K&R2 Sec. 5.4 p. 102; ANSI
  1290.     Sec. 4.1.5, Sec. 3.2.2.3; ISO Sec. 7.1.6, Sec. 6.2.2.3;
  1291.     Rationale Sec. 4.1.5; H&S Sec. 5.3.2 p. 122, Sec. 11.1 p. 292.
  1292.  
  1293.  
  1294. 5.5:    How should NULL be defined on a machine which uses a nonzero bit
  1295.     pattern as the internal representation of a null pointer?
  1296.  
  1297. A:    The same as on any other machine: as 0 (or ((void *)0)).
  1298.  
  1299.     Whenever a programmer requests a null pointer, either by writing
  1300.     "0" or "NULL," it is the compiler's responsibility to generate
  1301.     whatever bit pattern the machine uses for that null pointer.
  1302.     Therefore, #defining NULL as 0 on a machine for which internal
  1303.     null pointers are nonzero is as valid as on any other: the
  1304.     compiler must always be able to generate the machine's correct
  1305.     null pointers in response to unadorned 0's seen in pointer
  1306.     contexts.  See also questions 5.2, 5.10, and 5.17.
  1307.  
  1308.     References: ANSI Sec. 4.1.5; ISO Sec. 7.1.6; Rationale
  1309.     Sec. 4.1.5.
  1310.  
  1311. 5.6:    If NULL were defined as follows:
  1312.  
  1313.         #define NULL ((char *)0)
  1314.  
  1315.     wouldn't that make function calls which pass an uncast NULL
  1316.     work?
  1317.  
  1318. A:    Not in general.  The problem is that there are machines which
  1319.     use different internal representations for pointers to different
  1320.     types of data.  The suggested definition would make uncast NULL
  1321.     arguments to functions expecting pointers to characters work
  1322.     correctly, but pointer arguments of other types would still be
  1323.     problematical, and legal constructions such as
  1324.  
  1325.         FILE *fp = NULL;
  1326.  
  1327.     could fail.
  1328.  
  1329.     Nevertheless, ANSI C allows the alternate definition
  1330.  
  1331.         #define NULL ((void *)0)
  1332.  
  1333.     for NULL.  Besides potentially helping incorrect programs to
  1334.     work (but only on machines with homogeneous pointers, thus
  1335.     questionably valid assistance), this definition may catch
  1336.     programs which use NULL incorrectly (e.g. when the ASCII NUL
  1337.     character was really intended; see question 5.9).
  1338.  
  1339.     References: Rationale Sec. 4.1.5.
  1340.  
  1341. 5.9:    If NULL and 0 are equivalent as null pointer constants, which
  1342.     should I use?
  1343.  
  1344. A:    Many programmers believe that NULL should be used in all pointer
  1345.     contexts, as a reminder that the value is to be thought of as a
  1346.     pointer.  Others feel that the confusion surrounding NULL and 0
  1347.     is only compounded by hiding 0 behind a macro, and prefer to use
  1348.     unadorned 0 instead.  There is no one right answer.  (See also
  1349.     questions 9.2 and 17.10.)  C programmers must understand that
  1350.     NULL and 0 are interchangeable in pointer contexts, and that an
  1351.     uncast 0 is perfectly acceptable.  Any usage of NULL (as opposed
  1352.     to 0) should be considered a gentle reminder that a pointer is
  1353.     involved; programmers should not depend on it (either for their
  1354.     own understanding or the compiler's) for distinguishing pointer
  1355.     0's from integer 0's.
  1356.  
  1357.     NULL should *not* be used when another kind of 0 is required,
  1358.     even though it might work, because doing so sends the wrong
  1359.     stylistic message.  (Furthermore, ANSI allows the definition of
  1360.     NULL to be ((void *)0), which will not work at all in non-
  1361.     pointer contexts.)  In particular, do not use NULL when the
  1362.     ASCII null character (NUL) is desired.  Provide your own
  1363.     definition
  1364.  
  1365.         #define NUL '\0'
  1366.  
  1367.     if you must.
  1368.  
  1369.     References: K&R1 Sec. 5.4 pp. 97-8; K&R2 Sec. 5.4 p. 102.
  1370.  
  1371. 5.10:    But wouldn't it be better to use NULL (rather than 0), in case
  1372.     the value of NULL changes, perhaps on a machine with nonzero
  1373.     internal null pointers?
  1374.  
  1375. A:    No.  (Using NULL may be preferable, but not for this reason.)
  1376.     Although symbolic constants are often used in place of numbers
  1377.     because the numbers might change, this is *not* the reason that
  1378.     NULL is used in place of 0.  Once again, the language guarantees
  1379.     that source-code 0's (in pointer contexts) generate null
  1380.     pointers.  NULL is used only as a stylistic convention.  See
  1381.     questions 5.5 and 9.2.
  1382.  
  1383. 5.12:    I use the preprocessor macro
  1384.  
  1385.         #define Nullptr(type) (type *)0
  1386.  
  1387.     to help me build null pointers of the correct type.
  1388.  
  1389. A:    This trick, though popular and superficially attractive, does
  1390.     not buy much.  It is not needed in assignments and comparisons;
  1391.     see question 5.2.  It does not even save keystrokes.  Its use
  1392.     may suggest to the reader that the program's author is shaky on
  1393.     the subject of null pointers, requiring that the #definition of
  1394.     the macro, its invocations, and *all* other pointer usages be
  1395.     checked.  See also questions 9.1 and 10.2.
  1396.  
  1397. 5.13:    This is strange.  NULL is guaranteed to be 0, but the null
  1398.     pointer is not?
  1399.  
  1400. A:    When the term "null" or "NULL" is casually used, one of several
  1401.     things may be meant:
  1402.  
  1403.     1.    The conceptual null pointer, the abstract language concept
  1404.         defined in question 5.1.  It is implemented with...
  1405.  
  1406.     2.    The internal (or run-time) representation of a null
  1407.         pointer, which may or may not be all-bits-0 and which may
  1408.         be different for different pointer types.  The actual
  1409.         values should be of concern only to compiler writers.
  1410.         Authors of C programs never see them, since they use...
  1411.  
  1412.     3.    The null pointer constant, which is a constant integer 0
  1413.         (see question 5.2).  It is often hidden behind...
  1414.  
  1415.     4.    The NULL macro, which is #defined to be "0" or
  1416.         "((void *)0)" (see question 5.4).  Finally, as red
  1417.         herrings, we have...
  1418.  
  1419.     5.    The ASCII null character (NUL), which does have all bits
  1420.         zero, but has no necessary relation to the null pointer
  1421.         except in name; and...
  1422.  
  1423.     6.    The "null string," which is another name for the empty
  1424.         string ("").  Using the term "null string" can be
  1425.         confusing in C, because an empty string involves a null
  1426.         ('\0') character, but *not* a null pointer, which brings
  1427.         us full circle...
  1428.  
  1429.     This article uses the phrase "null pointer" (in lower case) for
  1430.     sense 1, the character "0" or the phrase "null pointer constant"
  1431.     for sense 3, and the capitalized word "NULL" for sense 4.
  1432.  
  1433. 5.14:    Why is there so much confusion surrounding null pointers?  Why
  1434.     do these questions come up so often?
  1435.  
  1436. A:    C programmers traditionally like to know more than they need to
  1437.     about the underlying machine implementation.  The fact that null
  1438.     pointers are represented both in source code, and internally to
  1439.     most machines, as zero invites unwarranted assumptions.  The use
  1440.     of a preprocessor macro (NULL) may seem to suggest that the
  1441.     value could change some day, or on some weird machine.  The
  1442.     construct "if(p == 0)" is easily misread as calling for
  1443.     conversion of p to an integral type, rather than 0 to a pointer
  1444.     type, before the comparison.  Finally, the distinction between
  1445.     the several uses of the term "null" (listed in question 5.13
  1446.     above) is often overlooked.
  1447.  
  1448.     One good way to wade out of the confusion is to imagine that C
  1449.     used a keyword (perhaps "nil", like Pascal) as a null pointer
  1450.     constant.  The compiler could either turn "nil" into the correct
  1451.     type of null pointer when it could determine the type from the
  1452.     source code, or complain when it could not.  Now in fact, in C
  1453.     the keyword for a null pointer constant is not "nil" but "0",
  1454.     which works almost as well, except that an uncast "0" in a non-
  1455.     pointer context generates an integer zero instead of an error
  1456.     message, and if that uncast 0 was supposed to be a null pointer
  1457.     constant, the code may not work.
  1458.  
  1459. 5.15:    I'm confused.  I just can't understand all this null pointer
  1460.     stuff.
  1461.  
  1462. A:    Follow these two simple rules:
  1463.  
  1464.     1.    When you want a null pointer constant in source code,
  1465.         use "0" or "NULL".
  1466.  
  1467.     2.    If the usage of "0" or "NULL" is an argument in a
  1468.         function call, cast it to the pointer type expected by
  1469.         the function being called.
  1470.  
  1471.     The rest of the discussion has to do with other people's
  1472.     misunderstandings, with the internal representation of null
  1473.     pointers (which you shouldn't need to know), and with ANSI C
  1474.     refinements.  Understand questions 5.1, 5.2, and 5.4, and
  1475.     consider 5.3, 5.9, 5.13, and 5.14, and you'll do fine.
  1476.  
  1477. 5.16:    Given all the confusion surrounding null pointers, wouldn't it
  1478.     be easier simply to require them to be represented internally by
  1479.     zeroes?
  1480.  
  1481. A:    If for no other reason, doing so would be ill-advised because it
  1482.     would unnecessarily constrain implementations which would
  1483.     otherwise naturally represent null pointers by special, nonzero
  1484.     bit patterns, particularly when those values would trigger
  1485.     automatic hardware traps for invalid accesses.
  1486.  
  1487.     Besides, what would such a requirement really accomplish?
  1488.     Proper understanding of null pointers does not require knowledge
  1489.     of the internal representation, whether zero or nonzero.
  1490.     Assuming that null pointers are internally zero does not make
  1491.     any code easier to write (except for a certain ill-advised usage
  1492.     of calloc(); see question 7.31).  Known-zero internal pointers
  1493.     would not obviate casts in function calls, because the *size* of
  1494.     the pointer might still be different from that of an int.  (If
  1495.     "nil" were used to request null pointers, as mentioned in
  1496.     question 5.14 above, the urge to assume an internal zero
  1497.     representation would not even arise.)
  1498.  
  1499. 5.17:    Seriously, have any actual machines really used nonzero null
  1500.     pointers, or different representations for pointers to different
  1501.     types?
  1502.  
  1503. A:    The Prime 50 series used segment 07777, offset 0 for the null
  1504.     pointer, at least for PL/I.  Later models used segment 0, offset
  1505.     0 for null pointers in C, necessitating new instructions such as
  1506.     TCNP (Test C Null Pointer), evidently as a sop to all the extant
  1507.     poorly-written C code which made incorrect assumptions.  Older,
  1508.     word-addressed Prime machines were also notorious for requiring
  1509.     larger byte pointers (char *'s) than word pointers (int *'s).
  1510.  
  1511.     The Eclipse MV series from Data General has three
  1512.     architecturally supported pointer formats (word, byte, and bit
  1513.     pointers), two of which are used by C compilers: byte pointers
  1514.     for char * and void *, and word pointers for everything else.
  1515.  
  1516.     Some Honeywell-Bull mainframes use the bit pattern 06000 for
  1517.     (internal) null pointers.
  1518.  
  1519.     The CDC Cyber 180 Series has 48-bit pointers consisting of a
  1520.     ring, segment, and offset.  Most users (in ring 11) have null
  1521.     pointers of 0xB00000000000.  It was common on old CDC ones-
  1522.     complement machines to use an all-one-bits word as a special
  1523.     flag for all kinds of data, including invalid addresses.
  1524.  
  1525.     The old HP 3000 series uses a different addressing scheme for
  1526.     byte addresses than for word addresses; like several of the
  1527.     machines above it therefore uses different representations for
  1528.     char * and void * pointers than for other pointers.
  1529.  
  1530.     The Symbolics Lisp Machine, a tagged architecture, does not even
  1531.     have conventional numeric pointers; it uses the pair <NIL, 0>
  1532.     (basically a nonexistent <object, offset> handle) as a C null
  1533.     pointer.
  1534.  
  1535.     Depending on the "memory model" in use, 8086-family processors
  1536.     (PC compatibles) may use 16-bit data pointers and 32-bit
  1537.     function pointers, or vice versa.
  1538.  
  1539.     Some 64-bit Cray machines represent int * in the lower 48 bits
  1540.     of a word; char * additionally uses the upper 16 bits to
  1541.     indicate a byte address within a word.
  1542.  
  1543.     References: K&R1 Sec. A14.4 p. 211.
  1544.  
  1545. 5.20:    What does a run-time "null pointer assignment" error mean?  How
  1546.     do I track it down?
  1547.  
  1548. A:    This message, which typically occurs with MS-DOS compilers (see,
  1549.     therefore, section 19) means that you've written, via a null
  1550.     (perhaps because uninitialized) pointer, to location 0.  (See
  1551.     also question 16.8.)
  1552.  
  1553.     A debugger may let you set a data breakpoint or watchpoint or
  1554.     something on location 0.  Alternatively, you could write a bit
  1555.     of code to stash away a copy of 20 or so bytes from location 0,
  1556.     and periodically check that the memory at location 0 hasn't
  1557.     changed.
  1558.  
  1559.  
  1560. Section 6.  Arrays and Pointers
  1561.  
  1562. 6.1:    I had the definition char a[6] in one source file, and in
  1563.     another I declared extern char *a.  Why didn't it work?
  1564.  
  1565. A:    The declaration extern char *a simply does not match the actual
  1566.     definition.  The type pointer-to-type-T is not the same as array-
  1567.     of-type-T.  Use extern char a[].
  1568.  
  1569.     References: ANSI Sec. 3.5.4.2; ISO Sec. 6.5.4.2; CT&P Sec. 3.3
  1570.     pp. 33-4, Sec. 4.5 pp. 64-5.
  1571.  
  1572. 6.2:    But I heard that char a[] was identical to char *a.
  1573.  
  1574. A:    Not at all.  (What you heard has to do with formal parameters to
  1575.     functions; see question 6.4.)  Arrays are not pointers.  The
  1576.     array declaration char a[6] requests that space for six
  1577.     characters be set aside, to be known by the name "a."  That is,
  1578.     there is a location named "a" at which six characters can sit.
  1579.     The pointer declaration char *p, on the other hand, requests a
  1580.     place which holds a pointer, to be known by the name "p."  This
  1581.     pointer can point almost anywhere: to any char, or to any
  1582.     contiguous array of chars, or nowhere (see also questions 5.1
  1583.     and 1.30).
  1584.  
  1585.     As usual, a picture is worth a thousand words.  The declarations
  1586.  
  1587.         char a[] = "hello";
  1588.         char *p = "world";
  1589.  
  1590.     would initialize data structures which could be represented like
  1591.     this:
  1592.            +---+---+---+---+---+---+
  1593.         a: | h | e | l | l | o |\0 |
  1594.            +---+---+---+---+---+---+
  1595.            +-----+     +---+---+---+---+---+---+
  1596.         p: |  *======> | w | o | r | l | d |\0 |
  1597.            +-----+     +---+---+---+---+---+---+
  1598.  
  1599.     It is important to realize that a reference like *x*[3]
  1600.     generates different code depending on whether *x* is an array or
  1601.     a pointer.  Given the declarations above, when the compiler sees
  1602.     the expression a[3], it emits code to start at the location "a,"
  1603.     move three past it, and fetch the character there.  When it sees
  1604.     the expression p[3], it emits code to start at the location "p,"
  1605.     fetch the pointer value there, add three to the pointer, and
  1606.     finally fetch the character pointed to.  In other words, a[3] is
  1607.     three places past (the start of) the object *named* a, while
  1608.     p[3] is three places past the object *pointed to* by p.  In the
  1609.     example above, both a[3] and p[3] happen to be the character
  1610.     'l', but the compiler gets there differently.
  1611.  
  1612.     References: K&R2 Sec. 5.5 p. 104; CT&P Sec. 4.5 pp. 64-5.
  1613.  
  1614. 6.3:    So what is meant by the "equivalence of pointers and arrays" in
  1615.     C?
  1616.  
  1617. A:    Much of the confusion surrounding arrays and pointers in C can
  1618.     be traced to a misunderstanding of this statement.  Saying that
  1619.     arrays and pointers are "equivalent" means neither that they are
  1620.     identical nor even interchangeable.
  1621.  
  1622.     "Equivalence" refers to the following key definition:
  1623.  
  1624.         An lvalue of type array-of-T which appears in an
  1625.         expression decays (with three exceptions) into a
  1626.         pointer to its first element; the type of the
  1627.         resultant pointer is pointer-to-T.
  1628.  
  1629.     (The exceptions are when the array is the operand of a sizeof or
  1630.     & operator, or is a string literal initializer for a character
  1631.     array.)
  1632.  
  1633.     As a consequence of this definition, the compiler doesn't apply
  1634.     the array subscripting operator [] that differently to arrays
  1635.     and pointers, after all.  In an expression of the form a[i], the
  1636.     array decays into a pointer, following the rule above, and is
  1637.     then subscripted just as would be a pointer variable in the
  1638.     expression p[i] (although the eventual memory accesses will be
  1639.     different, as explained in question 6.2).  If you were to assign
  1640.     the array's address to the pointer:
  1641.  
  1642.         p = a;
  1643.  
  1644.     then p[3] and a[3] would access the same element.
  1645.  
  1646.     See also question 6.8.
  1647.  
  1648.     References: K&R1 Sec. 5.3 pp. 93-6; K&R2 Sec. 5.3 p. 99; ANSI
  1649.     Sec. 3.2.2.1, Sec. 3.3.2.1, Sec. 3.3.6; ISO Sec. 6.2.2.1,
  1650.     Sec. 6.3.2.1, Sec. 6.3.6; H&S Sec. 5.4.1 p. 124.
  1651.  
  1652. 6.4:    Then why are array and pointer declarations interchangeable as
  1653.     function formal parameters?
  1654.  
  1655. A:    It's supposed to be a convenience.
  1656.  
  1657.     Since arrays decay immediately into pointers, an array is never
  1658.     actually passed to a function.  Allowing pointer parameters to
  1659.     be declared as arrays is a simply a way of making it look as
  1660.     though the array was being passed -- a programmer may wish to
  1661.     emphasize that a parameter is traditionally treated as if it
  1662.     were an array, or that an array (strictly speaking, the address)
  1663.     is traditionally passed.  As a convenience, therefore, any
  1664.     parameter declarations which "look like" arrays, e.g.
  1665.  
  1666.         f(a)
  1667.         char a[];
  1668.         { ... }
  1669.  
  1670.     are treated by the compiler as if they were pointers, since that
  1671.     is what the function will receive if an array is passed:
  1672.  
  1673.         f(a)
  1674.         char *a;
  1675.         { ... }
  1676.  
  1677.     This conversion holds only within function formal parameter
  1678.     declarations, nowhere else.  If the conversion bothers you,
  1679.     avoid it; many people have concluded that the confusion it
  1680.     causes outweighs the small advantage of having the declaration
  1681.     "look like" the call or the uses within the function.
  1682.  
  1683.     See also question 6.21.
  1684.  
  1685.     References: K&R1 Sec. 5.3 p. 95, Sec. A10.1 p. 205; K&R2
  1686.     Sec. 5.3 p. 100, Sec. A8.6.3 p. 218, Sec. A10.1 p. 226; ANSI
  1687.     Sec. 3.5.4.3, Sec. 3.7.1, Sec. 3.9.6; ISO Sec. 6.5.4.3,
  1688.     Sec. 6.7.1, Sec. 6.9.6; H&S Sec. 9.3 p. 271; CT&P Sec. 3.3 pp.
  1689.     33-4.
  1690.  
  1691. 6.7:    How can an array be an lvalue, if you can't assign to it?
  1692.  
  1693. A:    The ANSI C Standard defines a "modifiable lvalue," which an
  1694.     array is not.
  1695.  
  1696.     References: ANSI Sec. 3.2.2.1; ISO Sec. 6.2.2.1; Rationale
  1697.     Sec. 3.2.2.1; H&S Sec. 7.1 p. 179.
  1698.  
  1699. 6.8:    Practically speaking, what is the difference between arrays and
  1700.     pointers?
  1701.  
  1702. A:    Arrays automatically allocate space, but can't be relocated or
  1703.     resized.  Pointers must be explicitly assigned to point to
  1704.     allocated space (perhaps using malloc), but can be reassigned
  1705.     (i.e. pointed at different objects) at will, and have many other
  1706.     uses besides serving as the base of blocks of memory.
  1707.  
  1708.     Due to the so-called equivalence of arrays and pointers (see
  1709.     question 6.3), arrays and pointers often seem interchangeable,
  1710.     and in particular a pointer to a block of memory assigned by
  1711.     malloc is frequently treated (and can be referenced using [])
  1712.     exactly as if it were a true array.  See questions 6.14 and
  1713.     6.16.  (Be careful with sizeof, though.)
  1714.  
  1715.     See also questions 1.32 and 20.14.
  1716.  
  1717. 6.9:    Someone explained to me that arrays were really just constant
  1718.     pointers.
  1719.  
  1720. A:    This is a bit of an oversimplification.  An array name is
  1721.     "constant" in that it cannot be assigned to, but an array is
  1722.     *not* a pointer, as the discussion and pictures in question 6.2
  1723.     should make clear.  See also questions 6.3 and 6.8.
  1724.  
  1725. 6.11:    I came across some "joke" code containing the "expression"
  1726.     5["abcdef"] .  How can this be legal C?
  1727.  
  1728. A:    Yes, Virginia, array subscripting is commutative in C.  This
  1729.     curious fact follows from the pointer definition of array
  1730.     subscripting, namely that a[e] is identical to *((a)+(e)), for
  1731.     *any* two expressions a and e, as long as one of them is a
  1732.     pointer expression and one is integral.  This unsuspected
  1733.     commutativity is often mentioned in C texts as if it were
  1734.     something to be proud of, but it finds no useful application
  1735.     outside of the Obfuscated C Contest (see question 20.36).
  1736.  
  1737.     References: Rationale Sec. 3.3.2.1; H&S Sec. 5.4.1 p. 124,
  1738.     Sec. 7.4.1 pp. 186-7.
  1739.  
  1740. 6.12:    Since array references decay into pointers, if arr is an array,
  1741.     what's the difference between arr and &arr?
  1742.  
  1743. A:    The type.
  1744.  
  1745.     In Standard C, &arr yields a pointer, of type pointer-to-array-
  1746.     of-T, to the entire array.  (In pre-ANSI C, the & in &arr
  1747.     generally elicited a warning, and was generally ignored.)  Under
  1748.     all C compilers, a simple reference (without an explicit &) to
  1749.     an array yields a pointer, of type pointer-to-T, to the array's
  1750.     first element.  (See also questions 6.3, 6.13, and 6.18.)
  1751.  
  1752.     References: ANSI Sec. 3.2.2.1, Sec. 3.3.3.2; ISO Sec. 6.2.2.1,
  1753.     Sec. 6.3.3.2; Rationale Sec. 3.3.3.2; H&S Sec. 7.5.6 p. 198.
  1754.  
  1755. 6.13:    How do I declare a pointer to an array?
  1756.  
  1757. A:    Usually, you don't want to.  When people speak casually of a
  1758.     pointer to an array, they usually mean a pointer to its first
  1759.     element.
  1760.  
  1761.     Instead of a pointer to an array, consider using a pointer to
  1762.     one of the array's elements.  Arrays of type T decay into
  1763.     pointers to type T (see question 6.3), which is convenient;
  1764.     subscripting or incrementing the resultant pointer will access
  1765.     the individual members of the array.  True pointers to arrays,
  1766.     when subscripted or incremented, step over entire arrays, and
  1767.     are generally useful only when operating on arrays of arrays, if
  1768.     at all.  (See question 6.18.)
  1769.  
  1770.     If you really need to declare a pointer to an entire array, use
  1771.     something like "int (*ap)[N];" where N is the size of the array.
  1772.     (See also question 1.21.)  If the size of the array is unknown,
  1773.     N can in principle be omitted, but the resulting type, "pointer
  1774.     to array of unknown size," is useless.
  1775.  
  1776.     See also question 6.12 above.
  1777.  
  1778.     References: ANSI Sec. 3.2.2.1; ISO Sec. 6.2.2.1.
  1779.  
  1780. 6.14:    How can I set an array's size at compile time?
  1781.     How can I avoid fixed-sized arrays?
  1782.  
  1783. A:    The equivalence between arrays and pointers (see question 6.3)
  1784.     allows a pointer to malloc'ed memory to simulate an array
  1785.     quite effectively.  After executing
  1786.  
  1787.         #include <stdlib.h>
  1788.         int *dynarray = (int *)malloc(10 * sizeof(int));
  1789.  
  1790.     (and if the call to malloc() succeeds), you can reference
  1791.     dynarray[i] (for i from 0 to 9) just as if dynarray were a
  1792.     conventional, statically-allocated array (int a[10]).  See also
  1793.     question 6.16.
  1794.  
  1795. 6.15:    How can I declare local arrays of a size matching a passed-in
  1796.     array?
  1797.  
  1798. A:    You can't, in C.  Array dimensions must be compile-time
  1799.     constants.  (gcc provides parameterized arrays as an extension.)
  1800.     You'll have to use malloc(), and remember to call free() before
  1801.     the function returns.  See also questions 6.14, 6.16, 6.19,
  1802.     7.22, and maybe 7.32.
  1803.  
  1804.     References: ANSI Sec. 3.4, Sec. 3.5.4.2; ISO Sec. 6.4,
  1805.     Sec. 6.5.4.2.
  1806.  
  1807. 6.16:    How can I dynamically allocate a multidimensional array?
  1808.  
  1809. A:    It is usually best to allocate an array of pointers, and then
  1810.     initialize each pointer to a dynamically-allocated "row."  Here
  1811.     is a two-dimensional example:
  1812.  
  1813.         #include <stdlib.h>
  1814.  
  1815.         int **array1 = (int **)malloc(nrows * sizeof(int *));
  1816.         for(i = 0; i < nrows; i++)
  1817.             array1[i] = (int *)malloc(ncolumns * sizeof(int));
  1818.  
  1819.     (In real code, of course, all of malloc's return values would
  1820.     be checked.)
  1821.  
  1822.     You can keep the array's contents contiguous, while making later
  1823.     reallocation of individual rows difficult, with a bit of
  1824.     explicit pointer arithmetic:
  1825.  
  1826.         int **array2 = (int **)malloc(nrows * sizeof(int *));
  1827.         array2[0] = (int *)malloc(nrows * ncolumns * sizeof(int));
  1828.         for(i = 1; i < nrows; i++)
  1829.             array2[i] = array2[0] + i * ncolumns;
  1830.  
  1831.     In either case, the elements of the dynamic array can be
  1832.     accessed with normal-looking array subscripts: arrayx[i][j] (for
  1833.     0 <= i <= NROWS and 0 <= j <= NCOLUMNS).
  1834.  
  1835.     If the double indirection implied by the above schemes is for
  1836.     some reason unacceptable, you can simulate a two-dimensional
  1837.     array with a single, dynamically-allocated one-dimensional
  1838.     array:
  1839.  
  1840.         int *array3 = (int *)malloc(nrows * ncolumns * sizeof(int));
  1841.  
  1842.     However, you must now perform subscript calculations manually,
  1843.     accessing the i,jth element with array3[i * ncolumns + j].  (A
  1844.     macro could hide the explicit calculation, but invoking it would
  1845.     require parentheses and commas which wouldn't look exactly like
  1846.     multidimensional array syntax, and the macro would need access
  1847.     to at least one of the dimensions, as well.  See also question
  1848.     6.19.)
  1849.  
  1850.     Finally, you could use pointers to arrays:
  1851.  
  1852.         int (*array4)[NCOLUMNS] =
  1853.             (int (*)[NCOLUMNS])malloc(nrows * sizeof(*array4));
  1854.  
  1855.     but the syntax starts getting horrific and at most one dimension
  1856.     may be specified at run time.
  1857.  
  1858.     With all of these techniques, you may of course need to remember
  1859.     to free the arrays (which may take several steps; see question
  1860.     7.23) when they are no longer needed, and you cannot necessarily
  1861.     intermix dynamically-allocated arrays with conventional,
  1862.     statically-allocated ones (see question 6.20, and also question
  1863.     6.18).
  1864.  
  1865.     All of these techniques can also be extended to three or more
  1866.     dimensions.
  1867.  
  1868. 6.17:    Here's a neat trick: if I write
  1869.  
  1870.         int realarray[10];
  1871.         int *array = &realarray[-1];
  1872.  
  1873.     I can treat "array" as if it were a 1-based array.
  1874.  
  1875. A:    Although this technique is attractive (and was used in old
  1876.     editions of the book _Numerical Recipes in C_), it does not
  1877.     conform to the C standards.  Pointer arithmetic is defined only
  1878.     as long as the pointer points within the same allocated block of
  1879.     memory, or to the imaginary "terminating" element one past it;
  1880.     otherwise, the behavior is undefined, *even if the pointer is
  1881.     not dereferenced*.  The code above could fail if, while
  1882.     subtracting the offset, an illegal address were generated
  1883.     (perhaps because the address tried to "wrap around" past the
  1884.     beginning of some memory segment).
  1885.  
  1886.     References: K&R2 Sec. 5.3 p. 100, Sec. 5.4 pp. 102-3, Sec. A7.7
  1887.     pp. 205-6; ANSI Sec. 3.3.6; ISO Sec. 6.3.6; Rationale
  1888.     Sec. 3.2.2.3.
  1889.  
  1890. 6.18:    My compiler complained when I passed a two-dimensional array to
  1891.     a function expecting a pointer to a pointer.
  1892.  
  1893. A:    The rule (see question 6.3) by which arrays decay into pointers
  1894.     is not applied recursively.  An array of arrays (i.e. a two-
  1895.     dimensional array in C) decays into a pointer to an array, not a
  1896.     pointer to a pointer.  Pointers to arrays can be confusing, and
  1897.     must be treated carefully; see also question 6.13.  (The
  1898.     confusion is heightened by the existence of incorrect compilers,
  1899.     including some old versions of pcc and pcc-derived lints, which
  1900.     improperly accept assignments of multi-dimensional arrays to
  1901.     multi-level pointers.)
  1902.  
  1903.     If you are passing a two-dimensional array to a function:
  1904.  
  1905.         int array[NROWS][NCOLUMNS];
  1906.         f(array);
  1907.  
  1908.     the function's declaration must match:
  1909.  
  1910.         f(int a[][NCOLUMNS])
  1911.         { ... }
  1912.  
  1913.     or
  1914.  
  1915.         f(int (*ap)[NCOLUMNS])  /* ap is a pointer to an array */
  1916.         { ... }
  1917.  
  1918.     In the first declaration, the compiler performs the usual
  1919.     implicit parameter rewriting of "array of array" to "pointer to
  1920.     array" (see questions 6.3 and 6.4); in the second form the
  1921.     pointer declaration is explicit.  Since the called function does
  1922.     not allocate space for the array, it does not need to know the
  1923.     overall size, so the number of rows, NROWS, can be omitted.  The
  1924.     "shape" of the array is still important, so the column dimension
  1925.     NCOLUMNS (and, for three- or more dimensional arrays, the
  1926.     intervening ones) must be retained.
  1927.  
  1928.     If a function is already declared as accepting a pointer to a
  1929.     pointer, it is probably meaningless to pass a two-dimensional
  1930.     array directly to it.
  1931.  
  1932.     See also questions 6.12 and 6.15.
  1933.  
  1934.     References: K&R1 Sec. 5.10 p. 110; K&R2 Sec. 5.9 p. 113; H&S
  1935.     Sec. 5.4.3 p. 126.
  1936.  
  1937. 6.19:    How do I write functions which accept two-dimensional arrays
  1938.     when the "width" is not known at compile time?
  1939.  
  1940. A:    It's not easy.  One way is to pass in a pointer to the [0][0]
  1941.     element, along with the two dimensions, and simulate array
  1942.     subscripting "by hand:"
  1943.  
  1944.         f2(aryp, nrows, ncolumns)
  1945.         int *aryp;
  1946.         int nrows, ncolumns;
  1947.         { ... array[i][j] is accessed as aryp[i * ncolumns + j] ... }
  1948.  
  1949.     This function could be called with the array from question 6.18
  1950.     as
  1951.  
  1952.         f2(&array[0][0], NROWS, NCOLUMNS);
  1953.  
  1954.     It must be noted, however, that a program which performs
  1955.     multidimensional array subscripting "by hand" in this way is not
  1956.     in strict conformance with the ANSI C Standard; according to an
  1957.     official interpretation, the behavior of accessing
  1958.     (&array[0][0])[x] is not defined for x >= NCOLUMNS.
  1959.  
  1960.     gcc allows local arrays to be declared having sizes which are
  1961.     specified by a function's arguments, but this is a nonstandard
  1962.     extension.
  1963.  
  1964.     When you want to be able to use a function on multidimensional
  1965.     arrays of various sizes, one solution is to simulate all the
  1966.     arrays dynamically, as in question 6.16.
  1967.  
  1968.     See also questions 6.18, 6.20, and 6.15.
  1969.  
  1970.     References: ANSI Sec. 3.3.6; ISO Sec. 6.3.6.
  1971.  
  1972. 6.20:    How can I use statically- and dynamically-allocated
  1973.     multidimensional arrays interchangeably when passing them to
  1974.     functions?
  1975.  
  1976. A:    There is no single perfect method.  Given the declarations
  1977.  
  1978.         int array[NROWS][NCOLUMNS];
  1979.         int **array1;            /* ragged */
  1980.         int **array2;            /* contiguous */
  1981.         int *array3;            /* "flattened" */
  1982.         int (*array4)[NCOLUMNS];
  1983.  
  1984.     with the pointers initialized as in the code fragments in
  1985.     question 6.16, and functions declared as
  1986.  
  1987.         f1(int a[][NCOLUMNS], int nrows, int ncolumns);
  1988.         f2(int *aryp, int nrows, int ncolumns);
  1989.         f3(int **pp, int nrows, int ncolumns);
  1990.  
  1991.     where f1() accepts a conventional two-dimensional array, f2()
  1992.     accepts a "flattened" two-dimensional array, and f3() accepts a
  1993.     pointer-to-pointer, simulated array (see also questions 6.18 and
  1994.     6.19), the following calls should work as expected:
  1995.  
  1996.         f1(array, NROWS, NCOLUMNS);
  1997.         f1(array4, nrows, NCOLUMNS);
  1998.         f2(&array[0][0], NROWS, NCOLUMNS);
  1999.         f2(*array, NROWS, NCOLUMNS);
  2000.         f2(*array2, nrows, ncolumns);
  2001.         f2(array3, nrows, ncolumns);
  2002.         f2(*array4, nrows, NCOLUMNS);
  2003.         f3(array1, nrows, ncolumns);
  2004.         f3(array2, nrows, ncolumns);
  2005.  
  2006.     The following two calls would probably work on most systems, but
  2007.     involve questionable casts, and work only if the dynamic
  2008.     ncolumns matches the static NCOLUMNS:
  2009.  
  2010.         f1((int (*)[NCOLUMNS])(*array2), nrows, ncolumns);
  2011.         f1((int (*)[NCOLUMNS])array3, nrows, ncolumns);
  2012.  
  2013.     It must again be noted that passing &array[0][0] (or,
  2014.     equivalently, *array) to f2() is not strictly conforming; see
  2015.     question 6.19.
  2016.  
  2017.     If you can understand why all of the above calls work and are
  2018.     written as they are, and if you understand why the combinations
  2019.     that are not listed would not work, then you have a *very* good
  2020.     understanding of arrays and pointers in C.
  2021.  
  2022.     Rather than worrying about all of this, one approach to using
  2023.     multidimensional arrays of various sizes is to make them *all*
  2024.     dynamic, as in question 6.16.  If there are no static
  2025.     multidimensional arrays -- if all arrays are allocated like
  2026.     array1 or array2 in question 6.16 -- then all functions can be
  2027.     written like f3().
  2028.  
  2029. 6.21:    Why doesn't sizeof properly report the size of an array when the
  2030.     array is a parameter to a function?
  2031.  
  2032. A:    The compiler pretends that the array parameter was declared as a
  2033.     pointer (see question 6.4), and sizeof reports the size of the
  2034.     pointer.
  2035.  
  2036.     References: H&S Sec. 7.5.2 p. 195.
  2037.  
  2038.  
  2039. Section 7. Memory Allocation
  2040.  
  2041. 7.1:    Why doesn't this fragment work?
  2042.  
  2043.         char *answer;
  2044.         printf("Type something:\n");
  2045.         gets(answer);
  2046.         printf("You typed \"%s\"\n", answer);
  2047.  
  2048. A:    The pointer variable answer(), which is handed to gets() as the
  2049.     location into which the response should be stored, has not been
  2050.     set to point to any valid storage.  That is, we cannot say where
  2051.     the pointer answer() points.  (Since local variables are not
  2052.     initialized, and typically contain garbage, it is not even
  2053.     guaranteed that answer() starts out as a null pointer.  See
  2054.     questions 1.30 and 5.1.)
  2055.  
  2056.     The simplest way to correct the question-asking program is to
  2057.     use a local array, instead of a pointer, and let the compiler
  2058.     worry about allocation:
  2059.  
  2060.         #include <stdio.h>
  2061.         #include <string.h>
  2062.  
  2063.         char answer[100], *p;
  2064.         printf("Type something:\n");
  2065.         fgets(answer, sizeof answer, stdin);
  2066.         if((p = strchr(answer, '\n')) != NULL)
  2067.             *p = '\0';
  2068.         printf("You typed \"%s\"\n", answer);
  2069.  
  2070.     This example also uses fgets() instead of gets(), so that the
  2071.     end of the array cannot be overwritten.  (See question 12.23.
  2072.     Unfortunately for this example, fgets() does not automatically
  2073.     delete the trailing \n, as gets() would.)  It would also be
  2074.     possible to use malloc() to allocate the answer buffer.
  2075.  
  2076. 7.2:    I can't get strcat() to work.  I tried
  2077.  
  2078.         char *s1 = "Hello, ";
  2079.         char *s2 = "world!";
  2080.         char *s3 = strcat(s1, s2);
  2081.  
  2082.     but I got strange results.
  2083.  
  2084. A:    As in question 7.1 above, the main problem here is that space
  2085.     for the concatenated result is not properly allocated.  C does
  2086.     not provide an automatically-managed string type.  C compilers
  2087.     only allocate memory for objects explicitly mentioned in the
  2088.     source code (in the case of "strings," this includes character
  2089.     arrays and string literals).  The programmer must arrange for
  2090.     sufficient space for the results of run-time operations such as
  2091.     string concatenation, typically by declaring arrays, or by
  2092.     calling malloc().
  2093.  
  2094.     strcat() performs no allocation; the second string is appended
  2095.     to the first one, in place.  Therefore, one fix would be to
  2096.     declare the first string as an array:
  2097.  
  2098.         char s1[20] = "Hello, ";
  2099.  
  2100.     Since strcat() returns the value of its first argument (s1, in
  2101.     this case), the variable s3 is superfluous.
  2102.  
  2103.     The original call to strcat() in the question actually has two
  2104.     problems: the string literal pointed to by s1, besides not being
  2105.     big enough for any concatenated text, is not necessarily
  2106.     writable at all.  See question 1.32.
  2107.  
  2108.     References: CT&P Sec. 3.2 p. 32.
  2109.  
  2110. 7.3:    But the man page for strcat() says that it takes two char *'s as
  2111.     arguments.  How am I supposed to know to allocate things?
  2112.  
  2113. A:    In general, when using pointers you *always* have to consider
  2114.     memory allocation, if only to make sure that the compiler is
  2115.     doing it for you.  If a library function's documentation does
  2116.     not explicitly mention allocation, it is usually the caller's
  2117.     problem.
  2118.  
  2119.     The Synopsis section at the top of a Unix-style man page or in
  2120.     the ANSI C standard can be misleading.  The code fragments
  2121.     presented there are closer to the function definitions used by
  2122.     an implementor than the invocations used by the caller.  In
  2123.     particular, many functions which accept pointers (e.g. to
  2124.     structures or strings) are usually called with the address of
  2125.     some object (a structure, or an array -- see questions 6.3 and
  2126.     6.4).  Other common examples are time() (see question 13.12)
  2127.     and stat().
  2128.  
  2129. 7.5:    I have a function that is supposed to return a string, but when
  2130.     it returns to its caller, the returned string is garbage.
  2131.  
  2132. A:    Make sure that the pointed-to memory is properly allocated.  The
  2133.     returned pointer should be to a statically-allocated buffer, or
  2134.     to a buffer passed in by the caller, or to memory obtained with
  2135.     malloc(), but *not* to a local (automatic) array.  In other
  2136.     words, never do something like
  2137.  
  2138.         char *itoa(int n)
  2139.         {
  2140.             char retbuf[20];        /* WRONG */
  2141.             sprintf(retbuf, "%d", n);
  2142.             return retbuf;            /* WRONG */
  2143.         }
  2144.  
  2145.     One fix (which is imperfect, especially if the function in
  2146.     question is called recursively, or if several of its return
  2147.     values are needed simultaneously) would be to declare the return
  2148.     buffer as
  2149.  
  2150.             static char retbuf[20];
  2151.  
  2152.     See also questions 12.21 and 20.1.
  2153.  
  2154.     References: ANSI Sec. 3.1.2.4; ISO Sec. 6.1.2.4.
  2155.  
  2156. 7.6:    Why am I getting "warning: assignment of pointer from integer
  2157.     lacks a cast" for calls to malloc()?
  2158.  
  2159. A:    Have you #included <stdlib.h>, or otherwise arranged for
  2160.     malloc() to be declared properly?
  2161.  
  2162.     References: H&S Sec. 4.7 p. 101.
  2163.  
  2164. 7.7:    Why does some code carefully cast the values returned by malloc
  2165.     to the pointer type being allocated?
  2166.  
  2167. A:    Before ANSI/ISO Standard C introduced the void * generic pointer
  2168.     type, these casts were typically required to silence warnings
  2169.     (and perhaps induce conversions) when assigning between
  2170.     incompatible pointer types.  (Under ANSI/ISO Standard C, these
  2171.     casts are no longer necessary.)
  2172.  
  2173.     References: H&S Sec. 16.1 pp. 386-7.
  2174.  
  2175. 7.8:    I see code like
  2176.  
  2177.         char *p = malloc(strlen(s) + 1);
  2178.         strcpy(p, s);
  2179.  
  2180.     Shouldn't that be malloc((strlen(s) + 1) * sizeof(char))?
  2181.  
  2182. A:    It's never necessary to multiply by sizeof(char), since
  2183.     sizeof(char) is, by definition, exactly 1.  (On the other hand,
  2184.     multiplying by sizeof(char) doesn't hurt, and may help by
  2185.     introducing a size_t into the expression.)  See also question
  2186.     8.9.
  2187.  
  2188.     References: ANSI Sec. 3.3.3.4; ISO Sec. 6.3.3.4; H&S Sec. 7.5.2
  2189.     p. 195.
  2190.  
  2191. 7.14:    I've heard that some operating systems don't actually allocate
  2192.     malloc'ed memory until the program tries to use it.  Is this
  2193.     legal?
  2194.  
  2195. A:    It's hard to say.  The Standard doesn't say that systems can act
  2196.     this way, but it doesn't explicitly say that they can't, either.
  2197.  
  2198.     References: ANSI Sec. 4.10.3; ISO Sec. 7.10.3.
  2199.  
  2200. 7.16:    I'm allocating a large array for some numeric work, using the
  2201.     line
  2202.  
  2203.         double *array = malloc(256 * 256 * sizeof(double));
  2204.  
  2205.     malloc() isn't returning null, but the program is acting
  2206.     strangely, as if it's overwriting memory, or malloc() isn't
  2207.     allocating as much as I asked for, or something.
  2208.  
  2209. A:    Notice that 256 x 256 is 65,536, which will not fit in a 16-bit
  2210.     int, even before you multiply it by sizeof(double).  If you need
  2211.     to allocate this much memory, you'll have to be careful.  If
  2212.     size_t (the type accepted by malloc()) is a 32-bit type on your
  2213.     machine, but int is 16 bits, you might be able to get away with
  2214.     writing 256 * (256 * sizeof(double)) (see question 3.14).
  2215.     Otherwise, you'll have to break your data structure up into
  2216.     smaller chunks, or use a 32-bit machine, or use some nonstandard
  2217.     memory allocation routines.  See also question 19.23.
  2218.  
  2219. 7.17:    I've got 8 meg of memory in my PC.  Why can I only seem to
  2220.     malloc() 640K or so?
  2221.  
  2222. A:    Under the segmented architecture of PC compatibles, it can be
  2223.     difficult to use more than 640K with any degree of transparency.
  2224.     See also question 19.23.
  2225.  
  2226. 7.19:    My program is crashing, apparently somewhere down inside malloc,
  2227.     but I can't see anything wrong with it.
  2228.  
  2229. A:    It is unfortunately very easy to corrupt malloc's internal data
  2230.     structures, and the resulting problems can be stubborn.  The
  2231.     most common source of problems is writing more to a malloc'ed
  2232.     region than it was allocated to hold; a particularly common bug
  2233.     is to malloc(strlen(s)) instead of strlen(s) + 1.  Other
  2234.     problems may involve using pointers to freed storage, freeing
  2235.     pointers twice, freeing pointers not obtained from malloc, or
  2236.     trying to realloc a null pointer (see question 7.30).
  2237.  
  2238.     See also questions 7.26, 16.8, and 18.2.
  2239.  
  2240. 7.20:    You can't use dynamically-allocated memory after you free it,
  2241.     can you?
  2242.  
  2243. A:    No.  Some early documentation for malloc() stated that the
  2244.     contents of freed memory were "left undisturbed," but this ill-
  2245.     advised guarantee was never universal and is not required by the
  2246.     C Standard.
  2247.  
  2248.     Few programmers would use the contents of freed memory
  2249.     deliberately, but it is easy to do so accidentally.  Consider
  2250.     the following (correct) code for freeing a singly-linked list:
  2251.  
  2252.         struct list *listp, *nextp;
  2253.         for(listp = base; listp != NULL; listp = nextp) {
  2254.             nextp = listp->next;
  2255.             free((void *)listp);
  2256.         }
  2257.  
  2258.     and notice what would happen if the more-obvious loop iteration
  2259.     expression listp = listp->next were used, without the temporary
  2260.     nextp pointer.
  2261.  
  2262.     References: K&R2 Sec. 7.8.5 p. 167; ANSI Sec. 4.10.3; ISO
  2263.     Sec. 7.10.3; Rationale Sec. 4.10.3.2; H&S Sec. 16.2 p. 387; CT&P
  2264.     Sec. 7.10 p. 95.
  2265.  
  2266. 7.21:    Why isn't a pointer null after calling free()?
  2267.     How unsafe is it to use (assign, compare) a pointer value after
  2268.     it's been freed?
  2269.  
  2270. A:    When you call free(), the memory pointed to by the passed
  2271.     pointer is freed, but the value of the pointer in the caller
  2272.     remains unchanged, because C's pass-by-value semantics mean that
  2273.     called functions never permanently change the values of their
  2274.     arguments.  (See also question 4.8.)
  2275.  
  2276.     A pointer value which has been freed is, strictly speaking,
  2277.     invalid, and *any* use of it, even if is not dereferenced can
  2278.     theoretically lead to trouble, though as a quality of
  2279.     implementation issue, most implementations will probably not go
  2280.     out of their way to generate exceptions for innocuous uses of
  2281.     invalid pointers.
  2282.  
  2283.     References: ANSI Sec. 4.10.3; ISO Sec. 7.10.3; Rationale
  2284.     Sec. 3.2.2.3.
  2285.  
  2286. 7.22:    When I call malloc() to allocate memory for a local pointer, do
  2287.     I have to explicitly free() it?
  2288.  
  2289. A:    Yes.  Remember that a pointer is different from what it points
  2290.     to.  Local variables are deallocated when the function returns,
  2291.     but in the case of a pointer variable, this means that the
  2292.     pointer is deallocated, *not* what it points to.  Memory
  2293.     allocated with malloc() always persists until you explicitly
  2294.     free it.  In general, for every call to malloc(), there should
  2295.     be a corresponding call to free().
  2296.  
  2297. 7.23:    I'm allocating structures which contain pointers to other
  2298.     dynamically-allocated objects.  When I free a structure, do I
  2299.     have to free each subsidiary pointer first?
  2300.  
  2301. A:    Yes.  In general, you must arrange that each pointer returned
  2302.     from malloc() be individually passed to free(), exactly once (if
  2303.     it is freed at all).
  2304.  
  2305.     A good rule of thumb is that for each call to malloc() in a
  2306.     program, you should be able to point at the call to free() which
  2307.     frees the memory allocated by that malloc() call.
  2308.  
  2309.     See also question 7.24.
  2310.  
  2311. 7.24:    Must I free allocated memory before the program exits?
  2312.  
  2313. A:    You shouldn't have to.  A real operating system definitively
  2314.     reclaims all memory when a program exits.  Nevertheless, some
  2315.     personal computers are said not to reliably recover memory, and
  2316.     all that can be inferred from the ANSI/ISO C Standard is that
  2317.     this is a "quality of implementation issue."
  2318.  
  2319.     References: ANSI Sec. 4.10.3.2; ISO Sec. 7.10.3.2.
  2320.  
  2321. 7.25:    I have a program which mallocs and later frees a lot of memory,
  2322.     but memory usage (as reported by ps) doesn't seem to go back
  2323.     down.
  2324.  
  2325. A:    Most implementations of malloc/free do not return freed memory
  2326.     to the operating system (if there is one), but merely make it
  2327.     available for future malloc() calls within the same program.
  2328.  
  2329. 7.26:    How does free() know how many bytes to free?
  2330.  
  2331. A:    The malloc/free implementation remembers the size of each block
  2332.     allocated and returned, so it is not necessary to remind it of
  2333.     the size when freeing.
  2334.  
  2335. 7.27:    So can I query the malloc package to find out how big an
  2336.     allocated block is?
  2337.  
  2338. A:    Not portably.
  2339.  
  2340. 7.30:    Is it legal to pass a null pointer as the first argument to
  2341.     realloc()?  Why would you want to?
  2342.  
  2343. A:    ANSI C sanctions this usage (and the related realloc(..., 0),
  2344.     which frees), although several earlier implementations do not
  2345.     support it, so it may not be fully portable.  Passing an
  2346.     initially-null pointer to realloc() can make it easier to write
  2347.     a self-starting incremental allocation algorithm.
  2348.  
  2349.     References: ANSI Sec. 4.10.3.4; ISO Sec. 7.10.3.4; H&S Sec. 16.3
  2350.     p. 388.
  2351.  
  2352. 7.31:    What's the difference between calloc() and malloc()?  Is it safe
  2353.     to take advantage of calloc's zero-filling?  Does free() work
  2354.     on memory allocated with calloc(), or do you need a cfree()?
  2355.  
  2356. A:    calloc(m, n) is essentially equivalent to
  2357.  
  2358.         p = malloc(m * n);
  2359.         memset(p, 0, m * n);
  2360.  
  2361.     The zero fill is all-bits-zero, and does *not* therefore
  2362.     guarantee useful null pointer values (see section 5 of this
  2363.     list) or floating-point zero values.  free() is properly used to
  2364.     free the memory allocated by calloc().
  2365.  
  2366.     References: ANSI Sec. 4.10.3 to 4.10.3.2; ISO Sec. 7.10.3 to
  2367.     7.10.3.2; H&S Sec. 16.1 p. 386, Sec. 16.2 p. 386; PCS Sec. 11
  2368.     pp. 141,142.
  2369.  
  2370. 7.32:    What is alloca() and why is its use discouraged?
  2371.  
  2372. A:    alloca() allocates memory which is automatically freed when the
  2373.     function which called alloca() returns.  That is, memory
  2374.     allocated with alloca is local to a particular function's "stack
  2375.     frame" or context.
  2376.  
  2377.     alloca() cannot be written portably, and is difficult to
  2378.     implement on machines without a conventional stack.  Its use is
  2379.     problematical (and the obvious implementation on a stack-based
  2380.     machine fails) when its return value is passed directly to
  2381.     another function, as in fgets(alloca(100), 100, stdin).
  2382.  
  2383.     For these reasons, alloca() is not Standard and cannot be used
  2384.     in programs which must be widely portable, no matter how useful
  2385.     it might be.
  2386.  
  2387.     See also question 7.22.
  2388.  
  2389.     References: Rationale Sec. 4.10.3.
  2390.  
  2391.  
  2392. Section 8. Characters and Strings
  2393.  
  2394. 8.1:    Why doesn't
  2395.  
  2396.         strcat(string, '!');
  2397.  
  2398.     work?
  2399.  
  2400. A:    There is a very real difference between characters and strings,
  2401.     and strcat() concatenates *strings*.
  2402.  
  2403.     Characters in C are represented by small integers corresponding
  2404.     to their character set values (see also question 8.6 below).
  2405.     Strings are represented by arrays of characters; you usually
  2406.     manipulate a pointer to the first character of the array.  It is
  2407.     never correct to use one when the other is expected.  To append
  2408.     a ! to a string, use
  2409.  
  2410.         strcat(string, "!");
  2411.  
  2412.     See also questions 1.32, 7.2, and 16.6.
  2413.  
  2414.     References: CT&P Sec. 1.5 pp. 9-10.
  2415.  
  2416. 8.2:    I'm checking a string to see if it matches a particular value.
  2417.     Why isn't this code working?
  2418.  
  2419.         char *string;
  2420.         ...
  2421.         if(string == "value") {
  2422.             /* string matches "value" */
  2423.             ...
  2424.         }
  2425.  
  2426. A:    Strings in C are represented as arrays of characters, and C
  2427.     never manipulates (assigns, compares, etc.) arrays as a whole.
  2428.     The == operator in the code fragment above compares two pointers
  2429.     -- the value of the pointer variable string and a pointer to the
  2430.     string literal "value" -- to see if they are equal, that is, if
  2431.     they point to the same place.  They probably don't, so the
  2432.     comparison never succeeds.
  2433.  
  2434.     To compare two strings, you generally use the library function
  2435.     strcmp():
  2436.  
  2437.         if(strcmp(string, "value") == 0) {
  2438.             /* string matches "value" */
  2439.             ...
  2440.         }
  2441.  
  2442. 8.3:    If I can say
  2443.  
  2444.         char a[] = "Hello, world!";
  2445.  
  2446.     why can't I say
  2447.  
  2448.         char a[14];
  2449.         a = "Hello, world!";
  2450.  
  2451. A:    Strings are arrays, and you can't assign arrays directly.  Use
  2452.     strcpy() instead:
  2453.  
  2454.         strcpy(a, "Hello, world!");
  2455.  
  2456.     See also questions 1.32, 4.2, and 7.2.
  2457.  
  2458. 8.6:    How can I get the numeric (character set) value corresponding to
  2459.     a character, or vice versa?
  2460.  
  2461. A:    In C, characters are represented by small integers corresponding
  2462.     to their values (in the machine's character set), so you don't
  2463.     need a conversion routine: if you have the character, you have
  2464.     its value.
  2465.  
  2466. 8.9:    I think something's wrong with my compiler: I just noticed that
  2467.     sizeof('a') is 2, not 1 (i.e. not sizeof(char)).
  2468.  
  2469. A:    Perhaps surprisingly, character constants in C are of type int,
  2470.     so sizeof('a') is sizeof(int) (though it's different in C++).
  2471.     See also question 7.8.
  2472.  
  2473.     References: ANSI Sec. 3.1.3.4; ISO Sec. 6.1.3.4; H&S Sec. 2.7.3
  2474.     p. 29.
  2475.  
  2476.  
  2477. Section 9. Boolean Expressions
  2478.  
  2479. 9.1:    What is the right type to use for Boolean values in C?  Why
  2480.     isn't it a standard type?  Should I use #defines or enums for
  2481.     the true and false values?
  2482.  
  2483. A:    C does not provide a standard Boolean type, in part because
  2484.     picking one involves a space/time tradeoff which can best be
  2485.     decided by the programmer.  (Using an int may be faster, while
  2486.     using char may save data space.  Smaller types may make the
  2487.     generated code bigger or slower, though, if they require lots of
  2488.     conversions to and from int.)
  2489.  
  2490.     The choice between #defines and enumeration constants for the
  2491.     true/false values is arbitrary and not terribly interesting (see
  2492.     also questions 2.22 and 17.10).  Use any of
  2493.  
  2494.         #define TRUE  1            #define YES 1
  2495.         #define FALSE 0            #define NO  0
  2496.  
  2497.         enum bool {false, true};    enum bool {no, yes};
  2498.  
  2499.     or use raw 1 and 0, as long as you are consistent within one
  2500.     program or project.  (An enumeration may be preferable if your
  2501.     debugger shows the names of enumeration constants when examining
  2502.     variables.)
  2503.  
  2504.     Some people prefer variants like
  2505.  
  2506.         #define TRUE (1==1)
  2507.         #define FALSE (!TRUE)
  2508.  
  2509.     or define "helper" macros such as
  2510.  
  2511.         #define Istrue(e) ((e) != 0)
  2512.  
  2513.     These don't buy anything (see question 9.2 below; see also
  2514.     questions 5.12 and 10.2).
  2515.  
  2516. 9.2:    Isn't #defining TRUE to be 1 dangerous, since any nonzero value
  2517.     is considered "true" in C?  What if a built-in logical or
  2518.     relational operator "returns" something other than 1?
  2519.  
  2520. A:    It is true (sic) that any nonzero value is considered true in C,
  2521.     but this applies only "on input", i.e. where a Boolean value is
  2522.     expected.  When a Boolean value is generated by a built-in
  2523.     operator, it is guaranteed to be 1 or 0.  Therefore, the test
  2524.  
  2525.         if((a == b) == TRUE)
  2526.  
  2527.     would work as expected (as long as TRUE is 1), but it is
  2528.     obviously silly.  In general, explicit tests against TRUE and
  2529.     FALSE are inappropriate, because some library functions (notably
  2530.     isupper(), isalpha(), etc.) return, on success, a nonzero value
  2531.     which is *not* necessarily 1.  (Besides, if you believe that
  2532.     "if((a == b) == TRUE)" is an improvement over "if(a == b)", why
  2533.     stop there?  Why not use "if(((a == b) == TRUE) == TRUE)"?)  A
  2534.     good rule of thumb is to use TRUE and FALSE (or the like) only
  2535.     for assignment to a Boolean variable or function parameter, or
  2536.     as the return value from a Boolean function, but never in a
  2537.     comparison.
  2538.  
  2539.     The preprocessor macros TRUE and FALSE (and, of course, NULL)
  2540.     are used for code readability, not because the underlying values
  2541.     might ever change.  (See also questions 5.3 and 5.10.)
  2542.  
  2543.     On the other hand, Boolean values and definitions can evidently
  2544.     be confusing, and some programmers feel that TRUE and FALSE
  2545.     macros only compound the confusion.  (See also question 5.9.)
  2546.  
  2547.     References: K&R1 Sec. 2.6 p. 39, Sec. 2.7 p. 41; K&R2 Sec. 2.6
  2548.     p. 42, Sec. 2.7 p. 44, Sec. A7.4.7 p. 204, Sec. A7.9 p. 206;
  2549.     ANSI Sec. 3.3.3.3, Sec. 3.3.8, Sec. 3.3.9, Sec. 3.3.13,
  2550.     Sec. 3.3.14, Sec. 3.3.15, Sec. 3.6.4.1, Sec. 3.6.5; ISO
  2551.     Sec. 6.3.3.3, Sec. 6.3.8, Sec. 6.3.9, Sec. 6.3.13, Sec. 6.3.14,
  2552.     Sec. 6.3.15, Sec. 6.6.4.1, Sec. 6.6.5; H&S Sec. 7.5.4 pp. 196-7,
  2553.     Sec. 7.6.4 pp. 207-8, Sec. 7.6.5 pp. 208-9, Sec. 7.7 pp. 217-8,
  2554.     Sec. 7.8 pp. 218-9, Sec. 8.5 pp. 238-9, Sec. 8.6 pp. 241-4;
  2555.     "What the Tortoise Said to Achilles".
  2556.  
  2557. 9.3:    Is if(p), where p is a pointer, a valid conditional?
  2558.  
  2559. A:    Yes.  See question 5.3.
  2560.  
  2561.  
  2562. Section 10. C Preprocessor
  2563.  
  2564. 10.2:    Here are some cute preprocessor macros:
  2565.  
  2566.         #define begin    {
  2567.         #define end    }
  2568.  
  2569.     What do y'all think?
  2570.  
  2571. A:    Bleah.  See also section 17.
  2572.  
  2573. 10.3:    How can I write a generic macro to swap two values?
  2574.  
  2575. A:    There is no good answer to this question.  If the values are
  2576.     integers, a well-known trick using exclusive-OR could perhaps be
  2577.     used, but it will not work for floating-point values or
  2578.     pointers, or if the two values are the same variable (and the
  2579.     "obvious" supercompressed implementation for integral types
  2580.     a^=b^=a^=b is illegal due to multiple side-effects; see question
  2581.     3.2).  If the macro is intended to be used on values of
  2582.     arbitrary type (the usual goal), it cannot use a temporary,
  2583.     since it does not know what type of temporary it needs (and
  2584.     would have a hard time naming it if it did), and standard C does
  2585.     not provide a typeof operator.
  2586.  
  2587.     The best all-around solution is probably to forget about using a
  2588.     macro, unless you're willing to pass in the type as a third
  2589.     argument.
  2590.  
  2591. 10.4:    What's the best way to write a multi-statement macro?
  2592.  
  2593. A:    The usual goal is to write a macro that can be invoked as if it
  2594.     were a statement consisting of a single function call.  This
  2595.     means that the "caller" will be supplying the final semicolon,
  2596.     so the macro body should not.  The macro body cannot therefore
  2597.     be a simple brace-enclosed compound statement, because syntax
  2598.     errors would result if it were invoked (apparently as a single
  2599.     statement, but with a resultant extra semicolon) as the if
  2600.     branch of an if/else statement with an explicit else clause.
  2601.  
  2602.     The traditional solution, therefore, is to use
  2603.  
  2604.         #define MACRO(arg1, arg2) do {    \
  2605.             /* declarations */    \
  2606.             stmt1;            \
  2607.             stmt2;            \
  2608.             /* ... */        \
  2609.             } while(0)    /* (no trailing ; ) */
  2610.  
  2611.     When the caller appends a semicolon, this expansion becomes a
  2612.     single statement regardless of context.  (An optimizing compiler
  2613.     will remove any "dead" tests or branches on the constant
  2614.     condition 0, although lint may complain.)
  2615.  
  2616.     If all of the statements in the intended macro are simple
  2617.     expressions, with no declarations or loops, another technique is
  2618.     to write a single, parenthesized expression using one or more
  2619.     comma operators.  (For an example, see the first DEBUG() macro
  2620.     in question 10.26.)  This technique also allows a value to be
  2621.     "returned."
  2622.  
  2623.     References: H&S Sec. 3.3.2 p. 45; CT&P Sec. 6.3 pp. 82-3.
  2624.  
  2625. 10.6:    I'm splitting up a program into multiple source files for the
  2626.     first time, and I'm wondering what to put in .c files and what
  2627.     to put in .h files.  (What does ".h" mean, anyway?)
  2628.  
  2629. A:    As a general rule, you should put these things in header (.h)
  2630.     files:
  2631.  
  2632.         macro definitions (preprocessor #defines)
  2633.         structure, union, and enumeration declarations
  2634.         typedef declarations
  2635.         external function declarations (see also question 1.11)
  2636.         global variable declarations
  2637.  
  2638.     It's especially important to put a declaration or definition in
  2639.     a header file when it will be shared between several other
  2640.     files.  (In particular, never put external function prototypes
  2641.     in .c files.  See also question 1.7.)
  2642.  
  2643.     On the other hand, when a definition or declaration should
  2644.     remain private to one source file, it's fine to leave it there.
  2645.  
  2646.     See also questions 1.7 and 10.7.
  2647.  
  2648.     References: K&R2 Sec. 4.5 pp. 81-2; H&S Sec. 9.2.3 p. 267; CT&P
  2649.     Sec. 4.6 pp. 66-7.
  2650.  
  2651. 10.7:    Is it acceptable for one header file to #include another?
  2652.  
  2653. A:    It's a question of style, and thus receives considerable debate.
  2654.     Many people believe that "nested #include files" are to be
  2655.     avoided: the prestigious Indian Hill Style Guide (see question
  2656.     17.9) disparages them; they can make it harder to find relevant
  2657.     definitions; they can lead to multiple-definition errors if a
  2658.     file is #included twice; and they make manual Makefile
  2659.     maintenance very difficult.  On the other hand, they make it
  2660.     possible to use header files in a modular way (a header file can
  2661.     #include what it needs itself, rather than requiring each
  2662.     #includer to do so); a tool like grep (or a tags file) makes it
  2663.     easy to find definitions no matter where they are; a popular
  2664.     trick along the lines of:
  2665.  
  2666.         #ifndef HFILENAME_USED
  2667.         #define HFILENAME_USED
  2668.         ...header file contents...
  2669.         #endif
  2670.  
  2671.     (where a different bracketing macro name is used for each header
  2672.     file) makes a header file "idempotent" so that it can safely be
  2673.     #included multiple times; and automated Makefile maintenance
  2674.     tools (which are a virtual necessity in large projects anyway;
  2675.     see question 18.1) handle dependency generation in the face of
  2676.     nested #include files easily.  See also question 17.10.
  2677.  
  2678.     References: Rationale Sec. 4.1.2.
  2679.  
  2680. 10.8:    Where are header ("#include") files searched for?
  2681.  
  2682. A:    The exact behavior is implementation-defined (which means that
  2683.     it is supposed to be documented; see question 11.33).
  2684.     Typically, headers named with <> syntax are searched for in one
  2685.     or more standard places.  Header files named with "" syntax are
  2686.     first searched for in the "current directory," then (if not
  2687.     found) in the same standard places.
  2688.  
  2689.     Traditionally (especially under Unix compilers), the current
  2690.     directory is taken to be the directory containing the file
  2691.     containing the #include directive.  Under other compilers,
  2692.     however, the current directory (if any) is the directory in
  2693.     which the compiler was initially invoked.  Check your compiler
  2694.     documentation.
  2695.  
  2696.     References: K&R2 Sec. A12.4 p. 231; ANSI Sec. 3.8.2; ISO
  2697.     Sec. 6.8.2; H&S Sec. 3.4 p. 55.
  2698.  
  2699. 10.9:    I'm getting strange syntax errors on the very first declaration
  2700.     in a file, but it looks fine.
  2701.  
  2702. A:    Perhaps there's a missing semicolon at the end of the last
  2703.     declaration in the last header file you're #including.  See also
  2704.     questions 2.18 and 11.29.
  2705.  
  2706. 10.11:    I seem to be missing the system header file <sgtty.h>.  Can
  2707.     someone send me a copy?
  2708.  
  2709. A:    Standard headers exist in part so that definitions appropriate
  2710.     to your compiler, operating system, and processor can be
  2711.     supplied.  You cannot just pick up a copy of someone else's
  2712.     header file and expect it to work, unless that person is using
  2713.     exactly the same environment.  Ask your compiler vendor why the
  2714.     file was not provided (or to send a replacement copy).
  2715.  
  2716. 10.12:    How can I construct preprocessor #if expressions which compare
  2717.     strings?
  2718.  
  2719. A:    You can't do it directly; preprocessor #if arithmetic uses only
  2720.     integers.  You can #define several manifest constants, however,
  2721.     and implement  conditionals on those.
  2722.  
  2723.     See also question 20.17.
  2724.  
  2725.     References: K&R2 Sec. 4.11.3 p. 91; ANSI Sec. 3.8.1; ISO
  2726.     Sec. 6.8.1; H&S Sec. 7.11.1 p. 225.
  2727.  
  2728. 10.13:    Does the sizeof operator work in preprocessor #if directives?
  2729.  
  2730. A:    No.  Preprocessing happens during an earlier phase of
  2731.     compilation, before type names have been parsed.  Instead of
  2732.     sizeof, consider using the predefined constants in ANSI's
  2733.     <limits.h>, if applicable, or perhaps a "configure" script.
  2734.     (Better yet, try to write code which is inherently insensitive
  2735.     to type sizes.)
  2736.  
  2737.     References: ANSI Sec. 2.1.1.2, Sec. 3.8.1 footnote 83; ISO
  2738.     Sec. 5.1.1.2, Sec. 6.8.1; H&S Sec. 7.11.1 p. 225.
  2739.  
  2740. 10.14:    Can I use an #ifdef in a #define line, to define something two
  2741.     different ways?
  2742.  
  2743. A:    No.  You can't "run the preprocessor on itself," so to speak.
  2744.     What you can do is use one of two completely separate #define
  2745.     lines, depending on the #ifdef setting.
  2746.  
  2747.     References: ANSI Sec. 3.8.3, Sec. 3.8.3.4; ISO Sec. 6.8.3,
  2748.     Sec. 6.8.3.4; H&S Sec. 3.2 pp. 40-1.
  2749.  
  2750. 10.15:    Is there anything like an #ifdef for typedefs?
  2751.  
  2752. A:    Unfortunately, no.  (See also question 10.13.)
  2753.  
  2754.     References: ANSI Sec. 2.1.1.2, Sec. 3.8.1 footnote 83; ISO
  2755.     Sec. 5.1.1.2, Sec. 6.8.1; H&S Sec. 7.11.1 p. 225.
  2756.  
  2757. 10.16:    How can I use a preprocessor #if expression to tell if a machine
  2758.     is big-endian or little-endian?
  2759.  
  2760. A:    You probably can't.  (Preprocessor arithmetic uses only long
  2761.     integers, and there is no concept of addressing.  )  Are you
  2762.     sure you need to know the machine's endianness explicitly?
  2763.     Usually it's better to write code which doesn't care ).  See
  2764.     also question 20.9.
  2765.  
  2766.     References: ANSI Sec. 3.8.1; ISO Sec. 6.8.1; H&S Sec. 7.11.1
  2767.     p. 225.
  2768.  
  2769. 10.18:    I inherited some code which contains far too many #ifdef's for
  2770.     my taste.  How can I preprocess the code to leave only one
  2771.     conditional compilation set, without running it through the
  2772.     preprocessor and expanding all of the #include's and #define's
  2773.     as well?
  2774.  
  2775. A:    There are programs floating around called unifdef, rmifdef, and
  2776.     scpp ("selective C preprocessor") which do exactly this.  See
  2777.     question 18.16.
  2778.  
  2779. 10.19:    How can I list all of the pre#defined identifiers?
  2780.  
  2781. A:    There's no standard way, although it is a common need.  If the
  2782.     compiler documentation is unhelpful, the most expedient way is
  2783.     probably to extract printable strings from the compiler or
  2784.     preprocessor executable with something like the Unix strings
  2785.     utility.  Beware that many traditional system-specific
  2786.     pre#defined identifiers (e.g. "unix") are non-Standard (because
  2787.     they clash with the user's namespace) and are being removed or
  2788.     renamed.
  2789.  
  2790. 10.20:    I have some old code that tries to construct identifiers with a
  2791.     macro like
  2792.  
  2793.         #define Paste(a, b) a/**/b
  2794.  
  2795.     but it doesn't work any more.
  2796.  
  2797. A:    It was an undocumented feature of some early preprocessor
  2798.     implementations (notably John Reiser's) that comments
  2799.     disappeared entirely and could therefore be used for token
  2800.     pasting.  ANSI affirms (as did K&R1) that comments are replaced
  2801.     with white space.  However, since the need for pasting tokens
  2802.     was demonstrated and real, ANSI introduced a well-defined token-
  2803.     pasting operator, ##, which can be used like this:
  2804.  
  2805.         #define Paste(a, b) a##b
  2806.  
  2807.     See also question 11.17.
  2808.  
  2809.     References: ANSI Sec. 3.8.3.3; ISO Sec. 6.8.3.3; Rationale
  2810.     Sec. 3.8.3.3; H&S Sec. 3.3.9 p. 52.
  2811.  
  2812. 10.22:    Why is the macro
  2813.  
  2814.         #define TRACE(n) printf("TRACE: %d\n", n)
  2815.  
  2816.     giving me the warning "macro replacement within a string
  2817.     literal"?  It seems to be expanding
  2818.  
  2819.         TRACE(count);
  2820.     as
  2821.         printf("TRACE: %d\count", count);
  2822.  
  2823. A:    See question 11.18.
  2824.  
  2825. 10.23:    How can I use a macro argument inside a string literal in the
  2826.     macro expansion?
  2827.  
  2828. A:    See question 11.18.
  2829.  
  2830. 10.25:    I've got this tricky preprocessing I want to do and I can't
  2831.     figure out a way to do it.
  2832.  
  2833. A:    C's preprocessor is not intended as a general-purpose tool.
  2834.     (Note also that it is not guaranteed to be available as a
  2835.     separate program.)  Rather than forcing it to do something
  2836.     inappropriate, consider writing your own little special-purpose
  2837.     preprocessing tool, instead.  You can easily get a utility like
  2838.     make(1) to run it for you automatically.
  2839.  
  2840.     If you are trying to preprocess something other than C, consider
  2841.     using a general-purpose preprocessor.  (One older one available
  2842.     on most Unix systems is m4.)
  2843.  
  2844. 10.26:    How can I write a macro which takes a variable number of
  2845.     arguments?
  2846.  
  2847. A:    One popular trick is to define and invoke the macro with a
  2848.     single, parenthesized "argument" which in the macro expansion
  2849.     becomes the entire argument list, parentheses and all, for a
  2850.     function such as printf():
  2851.  
  2852.         #define DEBUG(args) (printf("DEBUG: "), printf args)
  2853.  
  2854.         if(n != 0) DEBUG(("n is %d\n", n));
  2855.  
  2856.     The obvious disadvantage is that the caller must always remember
  2857.     to use the extra parentheses.
  2858.  
  2859.     gcc has an extension which allows a function-like macro to
  2860.     accept a variable number of arguments, but it's not standard.
  2861.     Other possible solutions are to use different macros (DEBUG1,
  2862.     DEBUG2, etc.) depending on the number of arguments, to play
  2863.     games with commas:
  2864.  
  2865.         #define DEBUG(args) (printf("DEBUG: "), printf(args))
  2866.         #define _ ,
  2867.  
  2868.         DEBUG("i = %d" _ i)
  2869.  
  2870.     It is often better to use a bona-fide function, which can take a
  2871.     variable number of arguments in a well-defined way.  See
  2872.     questions 15.4 and 15.5.
  2873.  
  2874.  
  2875. Section 11.  ANSI/ISO Standard C
  2876.  
  2877. 11.1:    What is the "ANSI C Standard?"
  2878.  
  2879. A:    In 1983, the American National Standards Institute (ANSI)
  2880.     commissioned a committee, X3J11, to standardize the C language.
  2881.     After a long, arduous process, including several widespread
  2882.     public reviews, the committee's work was finally ratified as ANS
  2883.     X3.159-1989 on December 14, 1989, and published in the spring of
  2884.     1990.    For the most part, ANSI C standardizes existing practice,
  2885.     with a few additions from C++ (most notably function prototypes)
  2886.     and support for multinational character sets (including the
  2887.     controversial trigraph sequences).  The ANSI C standard also
  2888.     formalizes the C run-time library support routines.
  2889.  
  2890.     More recently, the Standard has been adopted as an international
  2891.     standard, ISO/IEC 9899:1990, and this ISO Standard replaces the
  2892.     earlier X3.159 even within the United States.  Its sections are
  2893.     numbered differently (briefly, ISO sections 5 through 7
  2894.     correspond roughly to the old ANSI sections 2 through 4).  As an
  2895.     ISO Standard, it is subject to ongoing revision through the
  2896.     release of Technical Corrigenda and Normative Addenda.
  2897.  
  2898.     In 1994, Technical Corrigendum 1 amended the Standard in about
  2899.     40 places, most of them minor corrections or clarifications.
  2900.     More recently, Normative Addendum 1 added about 50 pages of new
  2901.     material, mostly specifying new library functions for
  2902.     internationalization.  The production of Technical Corrigenda is
  2903.     an ongoing process, and a second one is expected in late 1995.
  2904.     In addition, both ANSI and ISO require periodic review of their
  2905.     standards.  This process is beginning in 1995, and will likely
  2906.     result in a completely revised standard (nicknamed "C9X," on the
  2907.     assumption of completion by 1999).
  2908.  
  2909.     The original ANSI Standard included a "Rationale," explaining
  2910.     many of its decisions, and discussing a number of subtle points,
  2911.     including several of those covered here.  (The Rationale was
  2912.     "not part of ANSI Standard X3.159-1989, but... included for
  2913.     information only," and is not included with the ISO Standard.)
  2914.  
  2915. 11.2:    How can I get a copy of the Standard?
  2916.  
  2917. A:    Copies are available in the United States from
  2918.  
  2919.         American National Standards Institute
  2920.         11 W. 42nd St., 13th floor
  2921.         New York, NY  10036  USA
  2922.         (+1) 212 642 4900
  2923.  
  2924.     and
  2925.  
  2926.         Global Engineering Documents
  2927.         15 Inverness Way E
  2928.         Englewood, CO  80112  USA
  2929.         (+1) 303 397 2715
  2930.         (800) 854 7179  (U.S. & Canada)
  2931.  
  2932.     In other countries, contact the appropriate national standards
  2933.     body, or ISO in Geneva at:
  2934.  
  2935.         ISO Sales
  2936.         Case Postale 56
  2937.         CH-1211 Geneve 20
  2938.         Switzerland
  2939.  
  2940.     (or see URL http://www.iso.ch or check the comp.std.internat FAQ
  2941.     list, Standards.Faq).
  2942.  
  2943.     At the time of this writing, the cost is $130.00 from ANSI or
  2944.     $410.00 from Global.  Copies of the original X3.159 (including
  2945.     the Rationale) may still be available at $205.00 from ANSI or
  2946.     $162.50 from Global.  Note that ANSI derives revenues to support
  2947.     its operations from the sale of printed standards, so electronic
  2948.     copies are *not* available.
  2949.  
  2950.     In the U.S., it may be possible to get a copy of the original
  2951.     ANSI X3.159 (including the Rationale) as "FIPS PUB 160" from
  2952.  
  2953.         National Technical Information Service (NTIS)
  2954.         U.S. Department of Commerce
  2955.         Springfield, VA  22161
  2956.         703 487 4650
  2957.  
  2958.     The mistitled _Annotated ANSI C Standard_, with annotations by
  2959.     Herbert Schildt, contains most of the text of ISO 9899; it is
  2960.     published by Osborne/McGraw-Hill, ISBN 0-07-881952-0, and sells
  2961.     in the U.S. for approximately $40.  It has been suggested that
  2962.     the price differential between this work and the official
  2963.     standard reflects the value of the annotations: they are plagued
  2964.     by numerous errors and omissions, and a few pages of the
  2965.     Standard itself are missing.  Many people on the net recommend
  2966.     ignoring the annotations entirely.  A review of the annotations
  2967.     ("annotated annotations") by Clive Feather can be found on the
  2968.     web at http://www.lysator.liu.se/c/schildt.html .
  2969.  
  2970.     The text of the Rationale (not the full Standard) can be
  2971.     obtained by anonymous ftp from ftp.uu.net (see question 18.16)
  2972.     in directory doc/standards/ansi/X3.159-1989, and is also
  2973.     available on the web at
  2974.     http://www.lysator.liu.se/c/rat/title.html .  The Rationale has
  2975.     also been printed by Silicon Press, ISBN 0-929306-07-4.
  2976.  
  2977. 11.3:    My ANSI compiler complains about a mismatch when it sees
  2978.  
  2979.         extern int func(float);
  2980.  
  2981.         int func(x)
  2982.         float x;
  2983.         { ...
  2984.  
  2985. A:    You have mixed the new-style prototype declaration
  2986.     "extern int func(float);" with the old-style definition
  2987.     "int func(x) float x;".  It is usually safe to mix the two
  2988.     styles (see question 11.4), but not in this case.
  2989.  
  2990.     Old C (and ANSI C, in the absence of prototypes, and in variable-
  2991.     length argument lists; see question 15.2) "widens" certain
  2992.     arguments when they are passed to functions.  floats are
  2993.     promoted to double, and characters and short integers are
  2994.     promoted to int.  (For old-style function definitions, the
  2995.     values are automatically converted back to the corresponding
  2996.     narrower types within the body of the called function, if they
  2997.     are declared that way there.)
  2998.  
  2999.     This problem can be fixed either by using new-style syntax
  3000.     consistently in the definition:
  3001.  
  3002.         int func(float x) { ... }
  3003.  
  3004.     or by changing the new-style prototype declaration to match the
  3005.     old-style definition:
  3006.  
  3007.         extern int func(double);
  3008.  
  3009.     (In this case, it would be clearest to change the old-style
  3010.     definition to use double as well, as long as the address of that
  3011.     parameter is not taken.)
  3012.  
  3013.     It may also be safer to avoid "narrow" (char, short int, and
  3014.     float) function arguments and return types altogether.
  3015.  
  3016.     See also question 1.25.
  3017.  
  3018.     References: K&R1 Sec. A7.1 p. 186; K&R2 Sec. A7.3.2 p. 202; ANSI
  3019.     Sec. 3.3.2.2, Sec. 3.5.4.3; ISO Sec. 6.3.2.2, Sec. 6.5.4.3;
  3020.     Rationale Sec. 3.3.2.2, Sec. 3.5.4.3; H&S Sec. 9.2 pp. 265-7,
  3021.     Sec. 9.4 pp. 272-3.
  3022.  
  3023. 11.4:    Can you mix old-style and new-style function syntax?
  3024.  
  3025. A:    Doing so is perfectly legal, as long as you're careful (see
  3026.     especially question 11.3).  Note however that old-style syntax
  3027.     is marked as obsolescent, so official support for it may be
  3028.     removed some day.
  3029.  
  3030.     References: ANSI Sec. 3.7.1, Sec. 3.9.5; ISO Sec. 6.7.1,
  3031.     Sec. 6.9.5; H&S Sec. 9.2.2 pp. 265-7, Sec. 9.2.5 pp. 269-70.
  3032.  
  3033. 11.5:    Why does the declaration
  3034.  
  3035.         extern f(struct x *p);
  3036.  
  3037.     give me an obscure warning message about "struct x introduced in
  3038.     prototype scope"?
  3039.  
  3040. A:    In a quirk of C's normal block scoping rules, a structure
  3041.     declared (or even mentioned) for the first time within a
  3042.     prototype cannot be compatible with other structures declared in
  3043.     the same source file (it goes out of scope at the end of the
  3044.     prototype).
  3045.  
  3046.     To resolve the problem, precede the prototype with the vacuous-
  3047.     looking declaration
  3048.  
  3049.         struct x;
  3050.  
  3051.     which places an (incomplete) declaration of struct x at file
  3052.     scope, so that all following declarations involving struct x can
  3053.     at least be sure they're referring to the same struct x.
  3054.  
  3055.     References: ANSI Sec. 3.1.2.1, Sec. 3.1.2.6, Sec. 3.5.2.3; ISO
  3056.     Sec. 6.1.2.1, Sec. 6.1.2.6, Sec. 6.5.2.3.
  3057.  
  3058. 11.8:    I don't understand why I can't use const values in initializers
  3059.     and array dimensions, as in
  3060.  
  3061.         const int n = 5;
  3062.         int a[n];
  3063.  
  3064. A:    The const qualifier really means "read-only;" an object so
  3065.     qualified is a run-time object which cannot (normally) be
  3066.     assigned to.  The value of a const-qualified object is therefore
  3067.     *not* a constant expression in the full sense of the term.  (C
  3068.     is unlike C++ in this regard.)  When you need a true compile-
  3069.     time constant, use a preprocessor #define.
  3070.  
  3071.     References: ANSI Sec. 3.4; ISO Sec. 6.4; H&S Secs. 7.11.2,7.11.3
  3072.     pp. 226-7.
  3073.  
  3074. 11.9:    What's the difference between "const char *p" and
  3075.     "char * const p"?
  3076.  
  3077. A:    "char const *p" declares a pointer to a constant character (you
  3078.     can't change the character); "char * const p" declares a
  3079.     constant pointer to a (variable) character (i.e. you can't
  3080.     change the pointer).
  3081.  
  3082.     Read these "inside out" to understand them; see also question
  3083.     1.21.
  3084.  
  3085.     References: ANSI Sec. 3.5.4.1 examples; ISO Sec. 6.5.4.1;
  3086.     Rationale Sec. 3.5.4.1; H&S Sec. 4.4.4 p. 81.
  3087.  
  3088. 11.10:    Why can't I pass a char ** to a function which expects a
  3089.     const char **?
  3090.  
  3091. A:    You can use a pointer-to-T (for any type T) where a pointer-to-
  3092.     const-T is expected.  However, the rule (an explicit exception)
  3093.     which permits slight mismatches in qualified pointer types is
  3094.     not applied recursively, but only at the top level.
  3095.  
  3096.     You must use explicit casts (e.g. (const char **) in this case)
  3097.     when assigning (or passing) pointers which have qualifier
  3098.     mismatches at other than the first level of indirection.
  3099.  
  3100.     References: ANSI Sec. 3.1.2.6, Sec. 3.3.16.1, Sec. 3.5.3; ISO
  3101.     Sec. 6.1.2.6, Sec. 6.3.16.1, Sec. 6.5.3; H&S Sec. 7.9.1 pp. 221-
  3102.     2.
  3103.  
  3104. 11.12:    Can I declare main() as void, to shut off these annoying "main
  3105.     returns no value" messages?
  3106.  
  3107. A:    No.  main() must be declared as returning an int, and as taking
  3108.     either zero or two arguments, of the appropriate types.  If
  3109.     you're calling exit() but still getting warnings, you may have
  3110.     to insert a redundant return statement (or use some kind of "not
  3111.     reached" directive, if available).
  3112.  
  3113.     Declaring a function as void does not merely shut off or
  3114.     rearrange warnings: it may also result in a different function
  3115.     call/return sequence, incompatible with what the caller (in
  3116.     main's case, the C run-time startup code) expects.
  3117.  
  3118.     (Note that this discussion of main() pertains only to "hosted"
  3119.     implementations; none of it applies to "freestanding"
  3120.     implementations, which may not even have main().  However,
  3121.     freestanding implementations are comparatively rare, and if
  3122.     you're using one, you probably know it.  If you've never heard
  3123.     of the distinction, you're probably using a hosted
  3124.     implementation, and the above rules apply.)
  3125.  
  3126.     References: ANSI Sec. 2.1.2.2.1, Sec. F.5.1; ISO Sec. 5.1.2.2.1,
  3127.     Sec. G.5.1; H&S Sec. 20.1 p. 416; CT&P Sec. 3.10 pp. 50-51.
  3128.  
  3129. 11.13:    But what about main's third argument, envp?
  3130.  
  3131. A:    It's a non-standard (though common) extension.  If you really
  3132.     need to access the environment in ways beyind what the standard
  3133.     getenv() function provides, though, the global variable environ
  3134.     is probably a better avenue (though it's equally non-standard).
  3135.  
  3136.     References: ANSI Sec. F.5.1; ISO Sec. G.5.1; H&S Sec. 20.1 pp.
  3137.     416-7.
  3138.  
  3139. 11.14:    I believe that declaring void main() can't fail, since I'm
  3140.     calling exit() instead of returning, and anyway my operating
  3141.     system ignores a program's exit/return status.
  3142.  
  3143. A:    It doesn't matter whether main() returns or not, or whether
  3144.     anyone looks at the status; the problem is that when main() is
  3145.     misdeclared, its caller (the runtime startup code) may not even
  3146.     be able to *call* it correctly (due to the potential clash of
  3147.     calling conventions; see question 11.12).  Your operating system
  3148.     may ignore the exit status, and void main() may work for you,
  3149.     but it is not portable and not correct.
  3150.  
  3151. 11.15:    The book I've been using, _C Programing for the Compleat Idiot_,
  3152.     always uses void main().
  3153.  
  3154. A:    Perhaps its author counts himself among the target audience.
  3155.     Many books unaccountably use void main() in examples.  They're
  3156.     wrong.
  3157.  
  3158. 11.16:    Is exit(status) truly equivalent to returning the same status
  3159.     from main()?
  3160.  
  3161. A:    Yes and no.  The Standard says that they are equivalent.
  3162.     However, a few older, nonconforming systems may have problems
  3163.     with one or the other form.  Also, a return from main() cannot
  3164.     be expected to work if data local to main() might be needed
  3165.     during cleanup; see also question 16.4.  (Finally, the two forms
  3166.     are obviously not equivalent in a recursive call to main().)
  3167.  
  3168.     References: K&R2 Sec. 7.6 pp. 163-4; ANSI Sec. 2.1.2.2.3; ISO
  3169.     Sec. 5.1.2.2.3.
  3170.  
  3171. 11.17:    I'm trying to use the ANSI "stringizing" preprocessing operator
  3172.     `#' to insert the value of a symbolic constant into a message,
  3173.     but it keeps stringizing the macro's name rather than its value.
  3174.  
  3175. A:    You can use something like the following two-step procedure to
  3176.     force a macro to be expanded as well as stringized:
  3177.  
  3178.         #define Str(x) #x
  3179.         #define Xstr(x) Str(x)
  3180.         #define OP plus
  3181.         char *opname = Xstr(OP);
  3182.  
  3183.     This code sets opname to "plus" rather than "OP".
  3184.  
  3185.     An equivalent circumlocution is necessary with the token-pasting
  3186.     operator ## when the values (rather than the names) of two
  3187.     macros are to be concatenated.
  3188.  
  3189.     References: ANSI Sec. 3.8.3.2, Sec. 3.8.3.5 example; ISO
  3190.     Sec. 6.8.3.2, Sec. 6.8.3.5.
  3191.  
  3192. 11.18:    What does the message "warning: macro replacement within a
  3193.     string literal" mean?
  3194.  
  3195. A:    Some pre-ANSI compilers/preprocessors interpreted macro
  3196.     definitions like
  3197.  
  3198.         #define TRACE(var, fmt) printf("TRACE: var = fmt\n", var)
  3199.  
  3200.     such that invocations like
  3201.  
  3202.         TRACE(i, %d);
  3203.  
  3204.     were expanded as
  3205.  
  3206.         printf("TRACE: i = %d\n", i);
  3207.  
  3208.     In other words, macro parameters were expanded even inside
  3209.     string literals and character constants.
  3210.  
  3211.     Macro expansion is *not* defined in this way by K&R or by
  3212.     Standard C.  When you do want to turn macro arguments into
  3213.     strings, you can use the new # preprocessing operator, along
  3214.     with string literal concatenation (another new ANSI feature):
  3215.  
  3216.         #define TRACE(var, fmt) \
  3217.             printf("TRACE: " #var " = " #fmt "\n", var)
  3218.  
  3219.     See also question 11.17 above.
  3220.  
  3221.     References: H&S Sec. 3.3.8 p. 51.
  3222.  
  3223. 11.19:    I'm getting strange syntax errors inside lines I've #ifdeffed
  3224.     out.
  3225.  
  3226. A:    Under ANSI C, the text inside a "turned off" #if, #ifdef, or
  3227.     #ifndef must still consist of "valid preprocessing tokens."
  3228.     This means that there must be no newlines inside quotes, and no
  3229.     unterminated comments or quotes (note particularly that an
  3230.     apostrophe within a contracted word looks like the beginning of
  3231.     a character constant).  Therefore, natural-language comments and
  3232.     pseudocode should always be written between the "official"
  3233.     comment delimiters /* and */.  (But see question 20.20, and also
  3234.     10.25.)
  3235.  
  3236.     References: ANSI Sec. 2.1.1.2, Sec. 3.1; ISO Sec. 5.1.1.2,
  3237.     Sec. 6.1; H&S Sec. 3.2 p. 40.
  3238.  
  3239. 11.20:    What are #pragmas and what are they good for?
  3240.  
  3241. A:    The #pragma directive provides a single, well-defined "escape
  3242.     hatch" which can be used for all sorts of implementation-
  3243.     specific controls and extensions: source listing control,
  3244.     structure packing, warning suppression (like lint's old
  3245.     /* NOTREACHED */ comments), etc.
  3246.  
  3247.     References: ANSI Sec. 3.8.6; ISO Sec. 6.8.6; H&S Sec. 3.7 p. 61.
  3248.  
  3249. 11.21:    What does "#pragma once" mean?  I found it in some header files.
  3250.  
  3251. A:    It is an extension implemented by some preprocessors to help
  3252.     make header files idempotent; it is essentially equivalent to
  3253.     the #ifndef trick mentioned in question 10.7.
  3254.  
  3255. 11.22:    Is char a[3] = "abc"; legal?  What does it mean?
  3256.  
  3257. A:    It is legal in ANSI C (and perhaps in a few pre-ANSI systems),
  3258.     though useful only in rare circumstances.  It declares an array
  3259.     of size three, initialized with the three characters 'a', 'b',
  3260.     and 'c', *without* the usual terminating '\0' character.  The
  3261.     array is therefore not a true C string and cannot be used with
  3262.     strcpy, printf %s, etc.
  3263.  
  3264.     Most of the time, you should let the compiler count the
  3265.     initializers when initializing arrays (in the case of the
  3266.     initializer "abc", of course, the computed size will be 4).
  3267.  
  3268.     References: ANSI Sec. 3.5.7; ISO Sec. 6.5.7; H&S Sec. 4.6.4 p.
  3269.     98.
  3270.  
  3271. 11.24:    Why can't I perform arithmetic on a void * pointer?
  3272.  
  3273. A:    The compiler doesn't know the size of the pointed-to objects.
  3274.     Before performing arithmetic, convert the pointer either to
  3275.     char * or to the pointer type you're trying to manipulate (but
  3276.     see also question 4.5).
  3277.  
  3278.     References: ANSI Sec. 3.1.2.5, Sec. 3.3.6; ISO Sec. 6.1.2.5,
  3279.     Sec. 6.3.6; H&S Sec. 7.6.2 p. 204.
  3280.  
  3281. 11.25:    What's the difference between memcpy() and memmove()?
  3282.  
  3283. A:    memmove() offers guaranteed behavior if the source and
  3284.     destination arguments overlap.  memcpy() makes no such
  3285.     guarantee, and may therefore be more efficiently implementable.
  3286.     When in doubt, it's safer to use memmove().
  3287.  
  3288.     References: K&R2 Sec. B3 p. 250; ANSI Sec. 4.11.2.1,
  3289.     Sec. 4.11.2.2; ISO Sec. 7.11.2.1, Sec. 7.11.2.2; Rationale
  3290.     Sec. 4.11.2; H&S Sec. 14.3 pp. 341-2; PCS Sec. 11 pp. 165-6.
  3291.  
  3292. 11.26:    What should malloc(0) do?  Return a null pointer or a pointer to
  3293.     0 bytes?
  3294.  
  3295. A:    The ANSI/ISO Standard says that it may do either; the behavior
  3296.     is implementation-defined (see question 11.33).
  3297.  
  3298.     References: ANSI Sec. 4.10.3; ISO Sec. 7.10.3; PCS Sec. 16.1 p.
  3299.     386.
  3300.  
  3301. 11.27:    Why does the ANSI Standard not guarantee more than six case-
  3302.     insensitive characters of external identifier significance?
  3303.  
  3304. A:    The problem is older linkers which are under the control of
  3305.     neither the ANSI/ISO Standard nor the C compiler developers on
  3306.     the systems which have them.  The limitation is only that
  3307.     identifiers be *significant* in the first six characters, not
  3308.     that they be restricted to six characters in length.  This
  3309.     limitation is annoying, but certainly not unbearable, and is
  3310.     marked in the Standard as "obsolescent," i.e. a future revision
  3311.     will likely relax it.
  3312.  
  3313.     This concession to current, restrictive linkers really had to be
  3314.     made, no matter how vehemently some people oppose it.  (The
  3315.     Rationale notes that its retention was "most painful.")  If you
  3316.     disagree, or have thought of a trick by which a compiler
  3317.     burdened with a restrictive linker could present the C
  3318.     programmer with the appearance of more significance in external
  3319.     identifiers, read the excellently-worded section 3.1.2 in the
  3320.     X3.159 Rationale (see question 11.1), which discusses several
  3321.     such schemes and explains why they could not be mandated.
  3322.  
  3323.     References: ANSI Sec. 3.1.2, Sec. 3.9.1; ISO Sec. 6.1.2,
  3324.     Sec. 6.9.1; Rationale Sec. 3.1.2; H&S Sec. 2.5 pp. 22-3.
  3325.  
  3326. 11.29:    My compiler is rejecting the simplest possible test programs,
  3327.     with all kinds of syntax errors.
  3328.  
  3329. A:    Perhaps it is a pre-ANSI compiler, unable to accept function
  3330.     prototypes and the like.
  3331.  
  3332.     See also questions 1.31, 10.9, and 11.30.
  3333.  
  3334. 11.30:    Why are some ANSI/ISO Standard library routines showing up as
  3335.     undefined, even though I've got an ANSI compiler?
  3336.  
  3337. A:    It's possible to have a compiler available which accepts ANSI
  3338.     syntax, but not to have ANSI-compatible header files or run-time
  3339.     libraries installed.  (In fact, this situation is rather common
  3340.     when using a non-vendor-supplied compiler such as gcc.)  See
  3341.     also questions 11.29, 13.25, and 13.26.
  3342.  
  3343. 11.31:    Does anyone have a tool for converting old-style C programs to
  3344.     ANSI C, or vice versa, or for automatically generating
  3345.     prototypes?
  3346.  
  3347. A:    Two programs, protoize and unprotoize, convert back and forth
  3348.     between prototyped and "old style" function definitions and
  3349.     declarations.  (These programs do *not* handle full-blown
  3350.     translation between "Classic" C and ANSI C.)  These programs are
  3351.     part of the FSF's GNU C compiler distribution; see question
  3352.     18.3.
  3353.  
  3354.     The unproto program (/pub/unix/unproto5.shar.Z on
  3355.     ftp.win.tue.nl) is a filter which sits between the preprocessor
  3356.     and the next compiler pass, converting most of ANSI C to
  3357.     traditional C on-the-fly.
  3358.  
  3359.     The GNU GhostScript package comes with a little program called
  3360.     ansi2knr.
  3361.  
  3362.     Before converting ANSI C back to old-style, beware that such a
  3363.     conversion cannot always be made both safely and automatically.
  3364.     ANSI C introduces new features and complexities not found in K&R
  3365.     C.  You'll especially need to be careful of prototyped function
  3366.     calls; you'll probably need to insert explicit casts.  See also
  3367.     questions 11.3 and 11.29.
  3368.  
  3369.     Several prototype generators exist, many as modifications to
  3370.     lint.  A program called CPROTO was posted to comp.sources.misc
  3371.     in March, 1992.  There is another program called "cextract."
  3372.     Many vendors supply simple utilities like these with their
  3373.     compilers.  See also question 18.16.  (But be careful when
  3374.     generating prototypes for old functions with "narrow"
  3375.     parameters; see question 11.3.)
  3376.  
  3377.     Finally, are you sure you really need to convert lots of old
  3378.     code to ANSI C?  The old-style function syntax is still
  3379.     acceptable, and a hasty conversion can easily introduce bugs.
  3380.     (See question 11.3.)
  3381.  
  3382. 11.32:    Why won't the Frobozz Magic C Compiler, which claims to be ANSI
  3383.     compliant, accept this code?  I know that the code is ANSI,
  3384.     because gcc accepts it.
  3385.  
  3386. A:    Many compilers support a few non-Standard extensions, gcc more
  3387.     so than most.  Are you sure that the code being rejected doesn't
  3388.     rely on such an extension?  It is usually a bad idea to perform
  3389.     experiments with a particular compiler to determine properties
  3390.     of a language; the applicable standard may permit variations, or
  3391.     the compiler may be wrong.  See also question 11.35.
  3392.  
  3393. 11.33:    People seem to make a point of distinguishing between
  3394.     implementation-defined, unspecified, and undefined behavior.
  3395.     What's the difference?
  3396.  
  3397. A:    Briefly: implementation-defined means that an implementation
  3398.     must choose some behavior and document it.  Unspecified means
  3399.     that an implementation should choose some behavior, but need not
  3400.     document it.  Undefined means that absolutely anything might
  3401.     happen.  In no case does the Standard impose requirements; in
  3402.     the first two cases it occasionally suggests (and may require a
  3403.     choice from among) a small set of likely behaviors.
  3404.  
  3405.     Note that since the Standard imposes *no* requirements on the
  3406.     behavior of a compiler faced with an instance of undefined
  3407.     behavior, the compiler can do absolutely anything.  In
  3408.     particular, there is no guarantee that the rest of the program
  3409.     will perform normally.  It's perilous to think that you can
  3410.     tolerate undefined behavior in a program; see question 3.2 for a
  3411.     relatively simple example.
  3412.  
  3413.     If you're interested in writing portable code, you can ignore
  3414.     the distinctions, as you'll want to avoid code that depends on
  3415.     any of the three behaviors.
  3416.  
  3417.     See also questions 3.9, and 11.34.
  3418.  
  3419.     References: ANSI Sec. 1.6; ISO Sec. 3.10, Sec. 3.16, Sec. 3.17;
  3420.     Rationale Sec. 1.6.
  3421.  
  3422. 11.34:    I'm appalled that the ANSI Standard leaves so many issues
  3423.     undefined.  Isn't a Standard's whole job to standardize these
  3424.     things?
  3425.  
  3426. A:    It has always been a characteristic of C that certain constructs
  3427.     behaved in whatever way a particular compiler or a particular
  3428.     piece of hardware chose to implement them.  This deliberate
  3429.     imprecision often allows compilers to generate more efficient
  3430.     code for common cases, without having to burden all programs
  3431.     with extra code to assure well-defined behavior of cases deemed
  3432.     to be less reasonable.  Therefore, the Standard is simply
  3433.     codifying existing practice.
  3434.  
  3435.     A programming language standard can be thought of as a treaty
  3436.     between the language user and the compiler implementor.  Parts
  3437.     of that treaty consist of features which the compiler
  3438.     implementor agrees to provide, and which the user may assume
  3439.     will be available.  Other parts, however, consist of rules which
  3440.     the user agrees to follow and which the implementor may assume
  3441.     will be followed.  As long as both sides uphold their
  3442.     guarantees, programs have a fighting chance of working
  3443.     correctly.  If *either* side reneges on any of its commitments,
  3444.     nothing is guaranteed to work.
  3445.  
  3446.     See also question 11.35.
  3447.  
  3448.     References: Rationale Sec. 1.1.
  3449.  
  3450. 11.35:    People keep saying that the behavior of i = i++ is undefined,
  3451.     but I just tried it on an ANSI-conforming compiler, and got the
  3452.     results I expected.
  3453.  
  3454. A:    A compiler may do anything it likes when faced with undefined
  3455.     behavior (and, within limits, with implementation-defined and
  3456.     unspecified behavior), including doing what you expect.  It's
  3457.     unwise to depend on it, though.  See also questions 11.32,
  3458.     11.33, and 11.34.
  3459.  
  3460.  
  3461. Section 12. Stdio
  3462.  
  3463. 12.1:    What's wrong with this code?
  3464.  
  3465.         char c;
  3466.         while((c = getchar()) != EOF) ...
  3467.  
  3468. A:    For one thing, the variable to hold getchar's return value
  3469.     must be an int.  getchar() can return all possible character
  3470.     values, as well as EOF.  By passing getchar's return value
  3471.     through a char, either a normal character might be
  3472.     misinterpreted as EOF, or the EOF might be altered (particularly
  3473.     if type char is unsigned) and so never seen.
  3474.  
  3475.     References: K&R1 Sec. 1.5 p. 14; K&R2 Sec. 1.5.1 p. 16; ANSI
  3476.     Sec. 3.1.2.5, Sec. 4.9.1, Sec. 4.9.7.5; ISO Sec. 6.1.2.5,
  3477.     Sec. 7.9.1, Sec. 7.9.7.5; H&S Sec. 5.1.3 p. 116, Sec. 15.1,
  3478.     Sec. 15.6; CT&P Sec. 5.1 p. 70; PCS Sec. 11 p. 157.
  3479.  
  3480. 12.2:    Why does the code
  3481.  
  3482.         while(!feof(infp)) {
  3483.             fgets(buf, MAXLINE, infp);
  3484.             fputs(buf, outfp);
  3485.         }
  3486.  
  3487.     copy the last line twice?
  3488.  
  3489. A:    In C, EOF is only indicated *after* an input routine has tried
  3490.     to read, and has reached end-of-file.  (In other words, C's I/O
  3491.     is not like Pascal's.)  Usually, you should just check the
  3492.     return value of the input routine (fgets() in this case); often,
  3493.     you don't need to use feof() at all.
  3494.  
  3495.     References: K&R2 Sec. 7.6 p. 164; ANSI Sec. 4.9.3, Sec. 4.9.7.1,
  3496.     Sec. 4.9.10.2; ISO Sec. 7.9.3, Sec. 7.9.7.1, Sec. 7.9.10.2; H&S
  3497.     Sec. 15.14 p. 382.
  3498.  
  3499. 12.4:    My program's prompts and intermediate output don't always show
  3500.     up on the screen, especially when I pipe the output through
  3501.     another program.
  3502.  
  3503. A:    It's best to use an explicit fflush(stdout) whenever output
  3504.     should definitely be visible.  Several mechanisms attempt to
  3505.     perform the fflush() for you, at the "right time," but they tend
  3506.     to apply only when stdout is an interactive terminal.  (See also
  3507.     question 12.24.)
  3508.  
  3509.     References: ANSI Sec. 4.9.5.2; ISO Sec. 7.9.5.2.
  3510.  
  3511. 12.5:    How can I read one character at a time, without waiting for the
  3512.     RETURN key?
  3513.  
  3514. A:    See question 19.1.
  3515.  
  3516. 12.6:    How can I print a '%' character in a printf format string?  I
  3517.     tried \%, but it didn't work.
  3518.  
  3519. A:    Simply double the percent sign: %% .
  3520.  
  3521.     \% can't work, because the backslash \ is the *compiler's*
  3522.     escape character, while here our problem is that the % is
  3523.     printf's escape character.
  3524.  
  3525.     See also question 19.17.
  3526.  
  3527.     References: K&R1 Sec. 7.3 p. 147; K&R2 Sec. 7.2 p. 154; ANSI
  3528.     Sec. 4.9.6.1; ISO Sec. 7.9.6.1.
  3529.  
  3530. 12.9:    Someone told me it was wrong to use %lf with printf().  How can
  3531.     printf() use %f for type double, if scanf() requires %lf?
  3532.  
  3533. A:    It's true that printf's %f specifier works with both float and
  3534.     double arguments.  Due to the "default argument promotions"
  3535.     (which apply in variable-length argument lists such as
  3536.     printf's, whether or not prototypes are in scope), values of
  3537.     type float are promoted to double, and printf() therefore sees
  3538.     only doubles.  See also questions 12.13 and 15.2.
  3539.  
  3540.     References: K&R1 Sec. 7.3 pp. 145-47, Sec. 7.4 pp. 147-50; K&R2
  3541.     Sec. 7.2 pp. 153-44, Sec. 7.4 pp. 157-59; ANSI Sec. 4.9.6.1,
  3542.     Sec. 4.9.6.2; ISO Sec. 7.9.6.1, Sec. 7.9.6.2; H&S Sec. 15.8 pp.
  3543.     357-64, Sec. 15.11 pp. 366-78; CT&P Sec. A.1 pp. 121-33.
  3544.  
  3545. 12.10:    How can I implement a variable field width with printf?  That
  3546.     is, instead of %8d, I want the width to be specified at run
  3547.     time.
  3548.  
  3549. A:    printf("%*d", width, n) will do just what you want.  See also
  3550.     question 12.15.
  3551.  
  3552.     References: K&R1 Sec. 7.3; K&R2 Sec. 7.2; ANSI Sec. 4.9.6.1; ISO
  3553.     Sec. 7.9.6.1; H&S Sec. 15.11.6; CT&P Sec. A.1.
  3554.  
  3555. 12.11:    How can I print numbers with commas separating the thousands?
  3556.     What about currency formatted numbers?
  3557.  
  3558. A:    The routines in <locale.h> begin to provide some support for
  3559.     these operations, but there is no standard routine for doing
  3560.     either task.  (The only thing printf() does in response to a
  3561.     custom locale setting is to change its decimal-point character.)
  3562.  
  3563.     References: ANSI Sec. 4.4; ISO Sec. 7.4; H&S Sec. 11.6 pp. 301-4.
  3564.  
  3565. 12.12:    Why doesn't the call scanf("%d", i) work?
  3566.  
  3567. A:    The arguments you pass to scanf() must always be pointers.
  3568.     To fix the fragment above, change it to scanf("%d", &i) .
  3569.  
  3570. 12.13:    Why doesn't this code:
  3571.  
  3572.         double d;
  3573.         scanf("%f", &d);
  3574.  
  3575.     work?
  3576.  
  3577. A:    Unlike printf(), scanf() uses %lf for values of type double, and
  3578.     %f for float.  See also question 12.9.
  3579.  
  3580. 12.15:    How can I specify a variable width in a scanf() format string?
  3581.  
  3582. A:    You can't; an asterisk in a scanf() format string means to
  3583.     suppress assignment.  You may be able to use ANSI stringizing
  3584.     and string concatenation to accomplish about the same thing, or
  3585.     to construct a scanf format string on-the-fly.
  3586.  
  3587. 12.17:    When I read numbers from the keyboard with scanf "%d\n", it
  3588.     seems to hang until I type one extra line of input.
  3589.  
  3590. A:    Perhaps surprisingly, \n in a scanf format string does *not*
  3591.     mean to expect a newline, but rather to read and discard
  3592.     characters as long as each is a whitespace character.  See also
  3593.     question 12.20.
  3594.  
  3595.     References: K&R2 Sec. B1.3 pp. 245-6; ANSI Sec. 4.9.6.2; ISO
  3596.     Sec. 7.9.6.2; H&S Sec. 15.8 pp. 357-64.
  3597.  
  3598. 12.18:    I'm reading a number with scanf %d and then a string with
  3599.     gets(), but the compiler seems to be skipping the call to
  3600.     gets()!
  3601.  
  3602. A:    scanf %d won't consume a trailing newline.  If the input number
  3603.     is immediately followed by a newline, that newline will
  3604.     immediately satisfy the gets().
  3605.  
  3606.     As a general rule, you shouldn't try to interlace calls to
  3607.     scanf() with calls to gets() (or any other input routines);
  3608.     scanf's peculiar treatment of newlines almost always leads to
  3609.     trouble.  Either use scanf() to read everything or nothing.
  3610.  
  3611.     See also questions 12.20 and 12.23.
  3612.  
  3613.     References: ANSI Sec. 4.9.6.2; ISO Sec. 7.9.6.2; H&S Sec. 15.8
  3614.     pp. 357-64.
  3615.  
  3616. 12.19:    I figured I could use scanf() more safely if I checked its
  3617.     return value to make sure that the user typed the numeric values
  3618.     I expect, but sometimes it seems to go into an infinite loop.
  3619.  
  3620. A:    When scanf() is attempting to convert numbers, any non-numeric
  3621.     characters it encounters terminate the conversion *and are left
  3622.     on the input stream*.  Therefore, unless some other steps are
  3623.     taken, unexpected non-numeric input "jams" scanf() again and
  3624.     again: scanf() never gets past the bad character(s) to encounter
  3625.     later, valid data.  If the user types a character like `x' in
  3626.     response to a numeric scanf format such as %d or %f, code that
  3627.     simply re-prompts and retries the same scanf() call will
  3628.     immediately reencounter the same `x'.
  3629.  
  3630.     See also question 12.20.
  3631.  
  3632.     References: ANSI Sec. 4.9.6.2; ISO Sec. 7.9.6.2; H&S Sec. 15.8
  3633.     pp. 357-64.
  3634.  
  3635. 12.20:    Why does everyone say not to use scanf()?  What should I use
  3636.     instead?
  3637.  
  3638. A:    scanf() has a number of problems -- see questions 12.17, 12.18,
  3639.     and 12.19.  Also, its %s format has the same problem that gets()
  3640.     has (see question 12.23) -- it's hard to guarantee that the
  3641.     receiving buffer won't overflow.
  3642.  
  3643.     More generally, scanf() is designed for relatively structured,
  3644.     formatted input (its name is in fact derived from "scan
  3645.     formatted").  If you pay attention, it will tell you whether it
  3646.     succeeded or failed, but it can tell you only approximately
  3647.     where it failed, and not at all how or why.  It's nearly
  3648.     impossible to do decent error recovery with scanf(); usually
  3649.     it's far easier to read entire lines (with fgets() or the like),
  3650.     then interpret them, either using sscanf() or some other
  3651.     techniques.  (Routines like strtol(), strtok(), and atoi() are
  3652.     often useful; see also question 13.6.)  If you do use sscanf(),
  3653.     don't forget to check the return value to make sure that the
  3654.     expected number of items were found.
  3655.  
  3656.     References: K&R2 Sec. 7.4 p. 159.
  3657.  
  3658. 12.21:    How can I tell how much destination buffer space I'll need for
  3659.     an arbitrary sprintf call?  How can I avoid overflowing the
  3660.     destination buffer with sprintf()?
  3661.  
  3662. A:    There are not (yet) any good answers to either of these
  3663.     excellent questions, and this represents perhaps the biggest
  3664.     deficiency in the traditional stdio library.
  3665.  
  3666.     When the format string being used with sprintf() is known and
  3667.     relatively simple, you can usually predict a buffer size in an
  3668.     ad-hoc way.  If the format consists of one or two %s's, you can
  3669.     count the fixed characters in the format string yourself (or let
  3670.     sizeof count them for you) and add in the result of calling
  3671.     strlen() on the string(s) to be inserted.  You can
  3672.     conservatively estimate the size that %d will expand to with
  3673.     code like:
  3674.  
  3675.         #include <limits.h>
  3676.         char buf[(sizeof(int) * CHAR_BIT + 2) / 3 + 1 + 1];
  3677.         sprintf(buf, "%d", n);
  3678.  
  3679.     (This code computes the number of characters required for a base-
  3680.     8 representation of a number; a base-10 expansion is guaranteed
  3681.     to take as much room or less.)
  3682.  
  3683.     When the format string is more complicated, or is not even known
  3684.     until run time, predicting the buffer size becomes as difficult
  3685.     as reimplementing sprintf(), and correspondingly error-prone
  3686.     (and inadvisable).  A last-ditch technique which is sometimes
  3687.     suggested is to use fprintf() to print the same text to a bit
  3688.     bucket or temporary file, and then to look at fprintf's return
  3689.     value or the size of the file (but see question 19.12).
  3690.  
  3691.     If there's any chance that the buffer might not be big enough,
  3692.     you won't want to call sprintf() without some guarantee that the
  3693.     buffer will not overflow and overwrite some other part of
  3694.     memory.  Several stdio's (including GNU and 4.4bsd) provide the
  3695.     obvious snprintf() function, which can be used like this:
  3696.  
  3697.         snprintf(buf, bufsize, "You typed \"%s\"", answer);
  3698.  
  3699.     and we can hope that a future revision of the ANSI/ISO C
  3700.     Standard will include this function.
  3701.  
  3702. 12.23:    Why does everyone say not to use gets()?
  3703.  
  3704. A:    Unlike fgets(), gets() cannot be told the size of the buffer
  3705.     it's to read into, so it cannot be prevented from overflowing
  3706.     that buffer.  As a general rule, always use fgets().  See
  3707.     question 7.1 for a code fragment illustrating the replacement of
  3708.     gets() with fgets().
  3709.  
  3710.     References: Rationale Sec. 4.9.7.2; H&S Sec. 15.7 p. 356.
  3711.  
  3712. 12.24:    Why does errno contain ENOTTY after a call to printf()?
  3713.  
  3714. A:    Many implementations of the stdio package adjust their behavior
  3715.     slightly if stdout is a terminal.  To make the determination,
  3716.     these implementations perform some operation which happens to
  3717.     fail (with ENOTTY) if stdout is not a terminal.  Although the
  3718.     output operation goes on to complete successfully, errno still
  3719.     contains ENOTTY.  (Note that it is only meaningful for a program
  3720.     to inspect the contents of errno after an error has been
  3721.     reported.)
  3722.  
  3723.     References: ANSI Sec. 4.1.3, Sec. 4.9.10.3; ISO Sec. 7.1.4,
  3724.     Sec. 7.9.10.3; CT&P Sec. 5.4 p. 73; PCS Sec. 14 p. 254.
  3725.  
  3726. 12.25:    What's the difference between fgetpos/fsetpos and ftell/fseek?
  3727.     What are fgetpos() and fsetpos() good for?
  3728.  
  3729. A:    fgetpos() and fsetpos() use a special typedef, fpos_t, for
  3730.     representing offsets (positions) in a file.  The type behind
  3731.     this typedef, if chosen appropriately, can represent arbitrarily
  3732.     large offsets, allowing fgetpos() and fsetpos() to be used with
  3733.     arbitrarily huge files.  ftell() and fseek(), on the other hand,
  3734.     use long int, and are therefore limited to offsets which can be
  3735.     represented in a long int.  See also question 1.4.
  3736.  
  3737.     References: K&R2 Sec. B1.6 p. 248; ANSI Sec. 4.9.1,
  3738.     Secs. 4.9.9.1,4.9.9.3; ISO Sec. 7.9.1, Secs. 7.9.9.1,7.9.9.3;
  3739.     H&S Sec. 15.5 p. 252.
  3740.  
  3741. 12.26:    How can I flush pending input so that a user's typeahead isn't
  3742.     read at the next prompt?  Will fflush(stdin) work?
  3743.  
  3744. A:    fflush() is defined only for output streams.  Since its
  3745.     definition of "flush" is to complete the writing of buffered
  3746.     characters (not to discard them), discarding unread input would
  3747.     not be an analogous meaning for fflush on input streams.
  3748.  
  3749.     There is no standard way to discard unread characters from a
  3750.     stdio input stream, nor would such a way be sufficient unread
  3751.     characters can also accumulate in other, OS-level input buffers.
  3752.  
  3753.     References: ANSI Sec. 4.9.5.2; ISO Sec. 7.9.5.2; H&S Sec. 15.2.
  3754.  
  3755. 12.30:    I'm trying to update a file in place, by using fopen mode "r+",
  3756.     reading a certain string, and writing back a modified string,
  3757.     but it's not working.
  3758.  
  3759. A:    Be sure to call fseek before you write, both to seek back to the
  3760.     beginning of the string you're trying to overwrite, and because
  3761.     an fseek or fflush is always required between reading and
  3762.     writing in the read/write "+" modes.  Also, remember that you
  3763.     can only overwrite characters with the same number of
  3764.     replacement characters; see also question 19.14.
  3765.  
  3766.     References: ANSI Sec. 4.9.5.3; ISO Sec. 7.9.5.3.
  3767.  
  3768. 12.33:    How can I redirect stdin or stdout to a file from within a
  3769.     program?
  3770.  
  3771. A:    Use freopen() (but see question 12.34 below).
  3772.  
  3773.     References: ANSI Sec. 4.9.5.4; ISO Sec. 7.9.5.4; H&S Sec. 15.2.
  3774.  
  3775. 12.34:    Once I've used freopen(), how can I get the original stdout (or
  3776.     stdin) back?
  3777.  
  3778. A:    There isn't a good way.  If you need to switch back, the best
  3779.     solution is not to have used freopen() in the first place.  Try
  3780.     using your own explicit output (or input) stream variable, which
  3781.     you can reassign at will, while leaving the original stdout (or
  3782.     stdin) undisturbed.
  3783.  
  3784. 12.38:    How can I read a binary data file properly?  I'm occasionally
  3785.     seeing 0x0a and 0x0d values getting garbled, and it seems to hit
  3786.     EOF prematurely if the data contains the value 0x1a.
  3787.  
  3788. A:    When you're reading a binary data file, you should specify "rb"
  3789.     mode when calling fopen(), to make sure that text file
  3790.     translations do not occur.  Similarly, when writing binary data
  3791.     files, use "wb".
  3792.  
  3793.     Note that the text/binary distinction is made when you open the
  3794.     file: once a file is open, it doesn't matter which I/O calls you
  3795.     use on it.  See also question 20.5.
  3796.  
  3797.     References: ANSI Sec. 4.9.5.3; ISO Sec. 7.9.5.3; H&S Sec. 15.2.1
  3798.     p. 348.
  3799.  
  3800.  
  3801. Section 13. Library Functions
  3802.  
  3803. 13.1:    How can I convert numbers to strings (the opposite of atoi)?  Is
  3804.     there an itoa function?
  3805.  
  3806. A:    Just use sprintf().  (Don't worry that sprintf() may be
  3807.     overkill, potentially wasting run time or code space; it works
  3808.     well in practice.)  See the examples in the answer to question
  3809.     7.5; see also question 12.21.
  3810.  
  3811.     You can obviously use sprintf() to convert long or floating-
  3812.     point numbers to strings as well (using %ld or %f).
  3813.  
  3814.     References: K&R1 Sec. 3.6 p. 60; K&R2 Sec. 3.6 p. 64.
  3815.  
  3816. 13.2:    Why does strncpy() not always place a '\0' terminator in the
  3817.     destination string?
  3818.  
  3819. A:    strncpy() was first designed to handle a now-obsolete data
  3820.     structure, the fixed-length, not-necessarily-\0-terminated
  3821.     "string."  (A related quirk of strncpy's is that it pads short
  3822.     strings with multiple \0's, out to the specified length.)
  3823.     strncpy() is admittedly a bit cumbersome to use in other
  3824.     contexts, since you must often append a '\0' to the destination
  3825.     string by hand.  You can get around the problem by using
  3826.     strncat() instead of strncpy(): if the destination string starts
  3827.     out empty, strncat() does what you probably wanted strncpy() to
  3828.     do.  Another possibility is sprintf(dest, "%.*s", n, source) .
  3829.  
  3830.     When arbitrary bytes (as opposed to strings) are being copied,
  3831.     memcpy() is usually a more appropriate routine to use than
  3832.     strncpy().
  3833.  
  3834. 13.5:    Why do some versions of toupper() act strangely if given an
  3835.     upper-case letter?
  3836.     Why does some code call islower() before toupper()?
  3837.  
  3838. A:    Older versions of toupper() and tolower() did not always work
  3839.     correctly on arguments which did not need converting (i.e. on
  3840.     digits or punctuation or letters already of the desired case).
  3841.     In ANSI/ISO Standard C, these functions are guaranteed to work
  3842.     appropriately on all character arguments.
  3843.  
  3844.     References: ANSI Sec. 4.3.2; ISO Sec. 7.3.2; H&S Sec. 12.9 pp.
  3845.     320-1; PCS p. 182.
  3846.  
  3847. 13.6:    How can I split up a string into whitespace-separated fields?
  3848.     How can I duplicate the process by which main() is handed argc
  3849.     and argv?
  3850.  
  3851. A:    The only Standard routine available for this kind of
  3852.     "tokenizing" is strtok, although it can be tricky to use and it
  3853.     may not do everything you want it to.  (For instance, it does
  3854.     not handle quoting.)
  3855.  
  3856.     References: K&R2 Sec. B3 p. 250; ANSI Sec. 4.11.5.8; ISO
  3857.     Sec. 7.11.5.8; H&S Sec. 13.7 pp. 333-4; PCS p. 178.
  3858.  
  3859. 13.7:    I need some code to do regular expression and wildcard matching.
  3860.  
  3861. A:    Make sure you recognize the difference between classic regular
  3862.     expressions (variants of which are used in such Unix utilities
  3863.     as ed and grep), and filename wildcards (variants of which are
  3864.     used by most operating systems).
  3865.  
  3866.     There are a number of packages available for matching regular
  3867.     expressions.  Most packages use a pair of functions, one for
  3868.     "compiling" the regular expression, and one for "executing" it
  3869.     (i.e. matching strings against it).  Look for header files named
  3870.     <regex.h> or <regexp.h>, and functions called regcmp()/regex(),
  3871.     regcomp()/regexec(), or re_comp()/re_exec().  (These functions
  3872.     may exist in a separate regexp library.)  A popular, freely-
  3873.     redistributable regexp package by Henry Spencer is available
  3874.     from ftp.cs.toronto.edu in pub/regexp.shar.Z or in several other
  3875.     archives.  The GNU project has a package called rx.  See also
  3876.     question 18.16.
  3877.  
  3878.     Filename wildcard matching (sometimes called "globbing") is done
  3879.     in a variety of ways on different systems.  On Unix, wildcards
  3880.     are automatically expanded by the shell before a process is
  3881.     invoked, so programs rarely have to worry about them explicitly.
  3882.     Under MS-DOS compilers, there is often a special object file
  3883.     which can be linked in to a program to expand wildcards while
  3884.     argv is being built.  Several systems (including MS-DOS and VMS)
  3885.     provide system services for listing or opening files specified
  3886.     by wildcards.  Check your compiler/library documentation.
  3887.  
  3888. 13.8:    I'm trying to sort an array of strings with qsort(), using
  3889.     strcmp() as the comparison function, but it's not working.
  3890.  
  3891. A:    By "array of strings" you probably mean "array of pointers to
  3892.     char."  The arguments to qsort's comparison function are
  3893.     pointers to the objects being sorted, in this case, pointers to
  3894.     pointers to char.  strcmp(), however, accepts simple pointers to
  3895.     char.  Therefore, strcmp() can't be used directly.  Write an
  3896.     intermediate comparison function like this:
  3897.  
  3898.         /* compare strings via pointers */
  3899.         int pstrcmp(const void *p1, const void *p2)
  3900.         {
  3901.             return strcmp(*(char * const *)p1, *(char * const *)p2);
  3902.         }
  3903.  
  3904.     The comparison function's arguments are expressed as "generic
  3905.     pointers," const void *.  They are converted back to what they
  3906.     "really are" (char **) and dereferenced, yielding char *'s which
  3907.     can be passed to strcmp().  (Under a pre-ANSI compiler, declare
  3908.     the pointer parameters as char * instead of void *, and drop the
  3909.     consts.)
  3910.  
  3911.     (Don't be misled by the discussion in K&R2 Sec. 5.11 pp. 119-20,
  3912.     which is not discussing the Standard library's qsort).
  3913.  
  3914.     References: ANSI Sec. 4.10.5.2; ISO Sec. 7.10.5.2; H&S Sec. 20.5
  3915.     p. 419.
  3916.  
  3917. 13.9:    Now I'm trying to sort an array of structures with qsort().  My
  3918.     comparison function takes pointers to structures, but the
  3919.     compiler complains that the function is of the wrong type for
  3920.     qsort().  How can I cast the function pointer to shut off the
  3921.     warning?
  3922.  
  3923. A:    The conversions must be in the comparison function, which must
  3924.     be declared as accepting "generic pointers" (const void *) as
  3925.     discussed in question 13.8 above.  The comparison function might
  3926.     look like
  3927.  
  3928.         int mystructcmp(const void *p1, const void *p2)
  3929.         {
  3930.             const struct mystruct *sp1 = p1;
  3931.             const struct mystruct *sp2 = p2;
  3932.             /* now compare sp1->whatever and sp2-> ... */
  3933.  
  3934.     (The conversions from generic pointers to struct mystruct
  3935.     pointers happen in the initializations sp1 = p1 and sp2 = p2;
  3936.     the compiler performs the conversions implicitly since p1 and p2
  3937.     are void pointers.  Explicit casts, and char * pointers, would
  3938.     be required under a pre-ANSI compiler.  See also question 7.7.)
  3939.  
  3940.     If, on the other hand, you're sorting pointers to structures,
  3941.     you'll need indirection, as in question 13.8:
  3942.     sp1 = *(struct mystruct **)p1 .
  3943.  
  3944.     In general, it is a bad idea to insert casts just to "shut the
  3945.     compiler up."  Compiler warnings are usually trying to tell you
  3946.     something, and unless you really know what you're doing, you
  3947.     ignore or muzzle them at your peril.  See also question 4.9.
  3948.  
  3949.     References: ANSI Sec. 4.10.5.2; ISO Sec. 7.10.5.2; H&S Sec. 20.5
  3950.     p. 419.
  3951.  
  3952. 13.10:    How can I sort a linked list?
  3953.  
  3954. A:    Sometimes it's easier to keep the list in order as you build it
  3955.     (or perhaps to use a tree instead).  Algorithms like insertion
  3956.     sort and merge sort lend themselves ideally to use with linked
  3957.     lists.  If you want to use a standard library function, you can
  3958.     allocate a temporary array of pointers, fill it in with pointers
  3959.     to all your list nodes, call qsort(), and finally rebuild the
  3960.     list pointers based on the sorted array.
  3961.  
  3962.     References: Knuth Sec. 5.2.1 pp. 80-102, Sec. 5.2.4 pp. 159-168;
  3963.     Sedgewick Sec. 8 pp. 98-100, Sec. 12 pp. 163-175.
  3964.  
  3965. 13.11:    How can I sort more data than will fit in memory?
  3966.  
  3967. A:    You want an "external sort," which you can read about in Knuth,
  3968.     Volume 3.  The basic idea is to sort the data in chunks (as much
  3969.     as will fit in memory at one time), write each sorted chunk to a
  3970.     temporary file, and then merge the files.  Your operating system
  3971.     may provide a general-purpose sort utility, and if so, you can
  3972.     try invoking it from within your program: see questions 19.27
  3973.     and 19.30.
  3974.  
  3975.     References: Knuth Sec. 5.4 pp. 247-378; Sedgewick Sec. 13 pp.
  3976.     177-187.
  3977.  
  3978. 13.12:    How can I get the current date or time of day in a C program?
  3979.  
  3980. A:    Just use the time, ctime, and/or localtime functions.  (These
  3981.     routines have been around for years, and are in the ANSI
  3982.     standard.)  Here is a simple example:
  3983.  
  3984.         #include <stdio.h>
  3985.         #include <time.h>
  3986.  
  3987.         main()
  3988.         {
  3989.             time_t now;
  3990.             time(&now);
  3991.             printf("It's %.24s.\n", ctime(&now));
  3992.             return 0;
  3993.         }
  3994.  
  3995.     References: K&R2 Sec. B10 pp. 255-7; ANSI Sec. 4.12; ISO
  3996.     Sec. 7.12; H&S Sec. 18.
  3997.  
  3998. 13.13:    I know that the library routine localtime() will convert a
  3999.     time_t into a broken-down struct tm, and that ctime() will
  4000.     convert a time_t to a printable string.  How can I perform the
  4001.     inverse operations of converting a struct tm or a string into a
  4002.     time_t?
  4003.  
  4004. A:    ANSI C specifies a library routine, mktime(), which converts a
  4005.     struct tm to a time_t.
  4006.  
  4007.     Converting a string to a time_t is harder, because of the wide
  4008.     variety of date and time formats which might be encountered.
  4009.     Some systems provide a strptime() function, which is basically
  4010.     the inverse of strftime().  Other popular routines are partime()
  4011.     (widely distributed with the RCS package) and getdate() (and a
  4012.     few others, from the C news distribution).  See question 18.16.
  4013.  
  4014.     References: K&R2 Sec. B10 p. 256; ANSI Sec. 4.12.2.3; ISO
  4015.     Sec. 7.12.2.3; H&S Sec. 18.4 pp. 401-2.
  4016.  
  4017. 13.14:    How can I add N days to a date?  How can I find the difference
  4018.     between two dates?
  4019.  
  4020. A:    The ANSI/ISO Standard C mktime() and difftime() functions
  4021.     provide some support for both problems.  mktime() accepts non-
  4022.     normalized dates, so it is straightforward to take a filled-in
  4023.     struct tm, add or subtract from the tm_mday field, and call
  4024.     mktime() to normalize the year, month, and day fields (and
  4025.     incidentally convert to a time_t value).  difftime() computes
  4026.     the difference, in seconds, between two time_t values; mktime()
  4027.     can be used to compute time_t values for two dates to be
  4028.     subtracted.
  4029.  
  4030.     These solutions are only guaranteed to work correctly for dates
  4031.     in the range which can be represented as time_t's.  The tm_mday
  4032.     field is an int, so day offsets of more than 32,736 or so may
  4033.     cause overflow.  Note also that at daylight saving time
  4034.     changeovers, local days are not 24 hours long.
  4035.  
  4036.     Another approach to both problems is to use "Julian day"
  4037.     numbers.  Implementations of Julian day routines can be found in
  4038.     the file JULCAL10.ZIP from the Simtel/Oakland archives (see
  4039.     question 18.16) and the "Date conversions" article mentioned in
  4040.     the References.
  4041.  
  4042.     See also questions 13.13, 20.31, and 20.32.
  4043.  
  4044.     References: K&R2 Sec. B10 p. 256; ANSI Secs. 4.12.2.2,4.12.2.3;
  4045.     ISO Secs. 7.12.2.2,7.12.2.3; H&S Secs. 18.4,18.5 pp. 401-2;
  4046.     David Burki, "Date Conversions".
  4047.  
  4048. 13.15:    I need a random number generator.
  4049.  
  4050. A:    The Standard C library has one: rand().  The implementation on
  4051.     your system may not be perfect, but writing a better one isn't
  4052.     necessarily easy, either.
  4053.  
  4054.     If you do find yourself needing to implement your own random
  4055.     number generator, there is plenty of literature out there; see
  4056.     the References.  There are also any number of packages on the
  4057.     net: look for r250, RANLIB, and FSULTRA (see question 18.16).
  4058.  
  4059.     References: K&R2 Sec. 2.7 p. 46, Sec. 7.8.7 p. 168; ANSI
  4060.     Sec. 4.10.2.1; ISO Sec. 7.10.2.1; H&S Sec. 17.7 p. 393; PCS
  4061.     Sec. 11 p. 172; Knuth Vol. 2 Chap. 3 pp. 1-177; Park and Miller,
  4062.     "Random Number Generators: Good Ones are hard to Find".
  4063.  
  4064. 13.16:    How can I get random integers in a certain range?
  4065.  
  4066. A:    The obvious way,
  4067.  
  4068.         rand() % N        /* POOR */
  4069.  
  4070.     (which tries to return numbers from 0 to N-1) is poor, because
  4071.     the low-order bits of many random number generators are
  4072.     distressingly *non*-random.  (See question 13.18.)  A better
  4073.     method is something like
  4074.  
  4075.         (int)((double)rand() / ((double)RAND_MAX + 1) * N)
  4076.  
  4077.     If you're worried about using floating point, you could use
  4078.  
  4079.         rand() / (RAND_MAX / N + 1)
  4080.  
  4081.     Both methods obviously require knowing RAND_MAX (which ANSI
  4082.     #defines in <stdlib.h>), and assume that N is much less than
  4083.     RAND_MAX.
  4084.  
  4085.     (Note, by the way, that RAND_MAX is a *constant* telling you
  4086.     what the fixed range of the C library rand() function is.  You
  4087.     cannot set RAND_MAX to some other value, and there is no way of
  4088.     requesting that rand() return numbers in some other range.)
  4089.  
  4090.     If you're starting with a random number generator which returns
  4091.     floating-point values between 0 and 1, all you have to do to get
  4092.     integers from 0 to N-1 is multiply the output of that generator
  4093.     by N.
  4094.  
  4095.     References: K&R2 Sec. 7.8.7 p. 168; PCS Sec. 11 p. 172.
  4096.  
  4097. 13.17:    Each time I run my program, I get the same sequence of numbers
  4098.     back from rand().
  4099.  
  4100. A:    You can call srand() to seed the pseudo-random number generator
  4101.     with a truly random initial value.  Popular seed values are the
  4102.     time of day, or the elapsed time before the user presses a key
  4103.     (although keypress times are hard to determine portably; see
  4104.     question 19.37).  (Note also that it's rarely useful to call
  4105.     srand() more than once during a run of a program; in particular,
  4106.     don't try calling srand() before each call to rand(), in an
  4107.     attempt to get "really random" numbers.)
  4108.  
  4109.     References: K&R2 Sec. 7.8.7 p. 168; ANSI Sec. 4.10.2.2; ISO
  4110.     Sec. 7.10.2.2; H&S Sec. 17.7 p. 393.
  4111.  
  4112. 13.18:    I need a random true/false value, so I'm just taking rand() % 2,
  4113.     but it's alternating 0, 1, 0, 1, 0...
  4114.  
  4115. A:    Poor pseudorandom number generators (such as the ones
  4116.     unfortunately supplied with some systems) are not very random in
  4117.     the low-order bits.  Try using the higher-order bits: see
  4118.     question 13.16.
  4119.  
  4120.     References: Knuth Sec. 3.2.1.1 pp. 12-14.
  4121.  
  4122. 13.20:    How can I generate random numbers with a normal or Gaussian
  4123.     distribution?
  4124.  
  4125. A:    Here is one method, by Box and Muller, and recommended by Knuth:
  4126.  
  4127.         #include <stdlib.h>
  4128.         #include <math.h>
  4129.  
  4130.         double gaussrand()
  4131.         {
  4132.             static double V1, V2, S;
  4133.             static int phase = 0;
  4134.             double X;
  4135.  
  4136.             if(phase == 0) {
  4137.                 do {
  4138.                     double U1 = (double)rand() / RAND_MAX;
  4139.                     double U2 = (double)rand() / RAND_MAX;
  4140.  
  4141.                     V1 = 2 * U1 - 1;
  4142.                     V2 = 2 * U2 - 1;
  4143.                     S = V1 * V1 + V2 * V2;
  4144.                     } while(S >= 1 || S == 0);
  4145.  
  4146.                 X = V1 * sqrt(-2 * log(S) / S);
  4147.             } else
  4148.                 X = V2 * sqrt(-2 * log(S) / S);
  4149.  
  4150.             phase = 1 - phase;
  4151.  
  4152.             return X;
  4153.         }
  4154.  
  4155.     See the extended versions of this list (see question 20.40) for
  4156.     other ideas.
  4157.  
  4158.     References: Knuth Sec. 3.4.1 p. 117; Box and Muller, "A Note on
  4159.     the Generation of Random Normal Deviates"; Press et al.,
  4160.     _Numerical Recipes in C_ Sec. 7.2 pp. 288-290.
  4161.  
  4162. 13.24:    I'm trying to port this         A:    Those routines are variously
  4163.     old program.  Why do I        obsolete; you should
  4164.     get "undefined external"    instead:
  4165.     errors for:
  4166.  
  4167.     index?                use strchr.
  4168.     rindex?                use strrchr.
  4169.     bcopy?                use memmove, after
  4170.                     interchanging the first and
  4171.                     second arguments (see also
  4172.                     question 11.25).
  4173.     bcmp?                use memcmp.
  4174.     bzero?                use memset, with a second
  4175.                     argument of 0.
  4176.  
  4177.     Contrariwise, if you're using an older system which is missing
  4178.     the functions in the second column, you may be able to implement
  4179.     them in terms of, or substitute, the functions in the first.
  4180.  
  4181.     References: PCS Sec. 11.
  4182.  
  4183. 13.25:    I keep getting errors due to library functions being undefined,
  4184.     but I'm #including all the right header files.
  4185.  
  4186. A:    In some cases (especially if the functions are nonstandard) you
  4187.     may have to explicitly ask for the correct libraries to be
  4188.     searched when you link the program.  See also questions 11.30,
  4189.     13.26, and 14.3.
  4190.  
  4191. 13.26:    I'm still getting errors due to library functions being
  4192.     undefined, even though I'm explicitly requesting the right
  4193.     libraries while linking.
  4194.  
  4195. A:    Many linkers make one pass over the list of object files and
  4196.     libraries you specify, and extract from libraries only those
  4197.     modules which satisfy references which have so far come up as
  4198.     undefined.  Therefore, the order in which libraries are listed
  4199.     with respect to object files (and each other) is significant;
  4200.     usually, you want to search the libraries last.  (For example,
  4201.     under Unix, put any -l options towards the end of the command
  4202.     line.)  See also question 13.28.
  4203.  
  4204. 13.28:    What does it mean when the linker says that _end is undefined?
  4205.  
  4206. A:    That message is a quirk of the old Unix linkers.  You only get
  4207.     an error about _end being undefined when other things are
  4208.     undefined, too -- fix the others, and the error about _end will
  4209.     disappear.  (See also questions 13.25 and 13.26.)
  4210.  
  4211.  
  4212. Section 14. Floating Point
  4213.  
  4214. 14.1:    When I set a float variable to, say, 3.1, why is printf()
  4215.     printing it as 3.0999999?
  4216.  
  4217. A:    Most computers use base 2 for floating-point numbers as well as
  4218.     for integers.  In base 2, 1/1010 (that is, 1/10 decimal) is an
  4219.     infinitely-repeating fraction: its binary representation is
  4220.     0.0001100110011... .  Depending on how carefully your compiler's
  4221.     binary/decimal conversion routines (such as those used by
  4222.     printf) have been written, you may see discrepancies when
  4223.     numbers (especially low-precision floats) not exactly
  4224.     representable in base 2 are assigned or read in and then printed
  4225.     (i.e. converted from base 10 to base 2 and back again).  See
  4226.     also question 14.6.
  4227.  
  4228. 14.2:    I'm trying to take some square roots, but I'm getting crazy
  4229.     numbers.
  4230.  
  4231. A:    Make sure that you have #included <math.h>, and correctly
  4232.     declared other functions returning double.  (Another library
  4233.     routine to be careful with is atof(), which is declared in
  4234.     <stdlib.h>.)  See also question 14.3 below.
  4235.  
  4236.     References: CT&P Sec. 4.5 pp. 65-6.
  4237.  
  4238. 14.3:    I'm trying to do some simple trig, and I am #including <math.h>,
  4239.     but I keep getting "undefined: sin" compilation errors.
  4240.  
  4241. A:    Make sure you're actually linking with the math library.  For
  4242.     instance, under Unix, you usually need to use the -lm option, at
  4243.     the *end* of the command line, when compiling/linking.  See also
  4244.     questions 13.25 and 13.26.
  4245.  
  4246. 14.4:    My floating-point calculations are acting strangely and giving
  4247.     me different answers on different machines.
  4248.  
  4249. A:    First, see question 14.2 above.
  4250.  
  4251.     If the problem isn't that simple, recall that digital computers
  4252.     usually use floating-point formats which provide a close but by
  4253.     no means exact simulation of real number arithmetic.  Underflow,
  4254.     cumulative precision loss, and other anomalies are often
  4255.     troublesome.
  4256.  
  4257.     Don't assume that floating-point results will be exact, and
  4258.     especially don't assume that floating-point values can be
  4259.     compared for equality.  (Don't throw haphazard "fuzz factors"
  4260.     in, either; see question 14.5.)
  4261.  
  4262.     These problems are no worse for C than they are for any other
  4263.     computer language.  Certain aspects of floating-point are
  4264.     usually defined as "however the processor does them" (see also
  4265.     question 11.34), otherwise a compiler for a machine without the
  4266.     "right" model would have to do prohibitively expensive
  4267.     emulations.
  4268.  
  4269.     This article cannot begin to list the pitfalls associated with,
  4270.     and workarounds appropriate for, floating-point work.  A good
  4271.     numerical programming text should cover the basics; see also the
  4272.     references below.
  4273.  
  4274.     References: Kernighan and Plauger, _The Elements of Programming
  4275.     Style_ Sec. 6 pp. 115-8; Knuth, Volume 2 chapter 4; David
  4276.     Goldberg, "What Every Computer Scientist Should Know about
  4277.     Floating-Point Arithmetic".
  4278.  
  4279. 14.5:    What's a good way to check for "close enough" floating-point
  4280.     equality?
  4281.  
  4282. A:    Since the absolute accuracy of floating point values varies, by
  4283.     definition, with their magnitude, the best way of comparing two
  4284.     floating point values is to use an accuracy threshold which is
  4285.     relative to the magnitude of the numbers being compared.  Rather
  4286.     than
  4287.  
  4288.         double a, b;
  4289.         ...
  4290.         if(a == b)    /* WRONG */
  4291.  
  4292.     use something like
  4293.  
  4294.         #include <math.h>
  4295.  
  4296.         if(fabs(a - b) <= epsilon * a)
  4297.  
  4298.     for some suitably-chosen epsilon.
  4299.  
  4300.     References: Knuth Sec. 4.2.2 pp. 217-8.
  4301.  
  4302. 14.6:    How do I round numbers?
  4303.  
  4304. A:    The simplest and most straightforward way is with code like
  4305.  
  4306.         (int)(x + 0.5)
  4307.  
  4308.     This technique won't work properly for negative numbers, though.
  4309.  
  4310. 14.7:    Why doesn't C have an exponentiation operator?
  4311.  
  4312. A:    Because few processors have an exponentiation instruction.  C
  4313.     has a pow() function, declared in <math.h>, although explicit
  4314.     multiplication is often better for small positive integral
  4315.     exponents.
  4316.  
  4317.     References: ANSI Sec. 4.5.5.1; ISO Sec. 7.5.5.1; H&S Sec. 17.6
  4318.     p. 393.
  4319.  
  4320. 14.8:    The pre-#defined constant M_PI seems to be missing from my
  4321.     machine's copy of <math.h>.
  4322.  
  4323. A:    That constant (which is apparently supposed to be the value of
  4324.     pi, accurate to the machine's precision), is not standard.  If
  4325.     you need pi, you'll have to #define it yourself.
  4326.  
  4327.     References: PCS Sec. 13 p. 237.
  4328.  
  4329. 14.9:    How do I test for IEEE NaN and other special values?
  4330.  
  4331. A:    Many systems with high-quality IEEE floating-point
  4332.     implementations provide facilities (e.g. predefined constants,
  4333.     and functions like isnan(), either as nonstandard extensions in
  4334.     <math.h> or perhaps in <ieee.h> or <nan.h>) to deal with these
  4335.     values cleanly, and work is being done to formally standardize
  4336.     such facilities.  A crude but usually effective test for NaN is
  4337.     exemplified by
  4338.  
  4339.         #define isnan(x) ((x) != (x))
  4340.  
  4341.     although non-IEEE-aware compilers may optimize the test away.
  4342.  
  4343.     Another possibility is to to format the value in question using
  4344.     sprintf(): on many systems it generates strings like "NaN" and
  4345.     "Inf" which you could compare for in a pinch.
  4346.  
  4347.     See also question 19.39.
  4348.  
  4349. 14.11:    What's a good way to implement complex numbers in C?
  4350.  
  4351. A:    It is straightforward to define a simple structure and some
  4352.     arithmetic functions to manipulate them.  See also questions
  4353.     2.7, 2.10, and 14.12.
  4354.  
  4355. 14.12:    I'm looking for some code to do:
  4356.         Fast Fourier Transforms (FFT's)
  4357.         matrix arithmetic (multiplication, inversion, etc.)
  4358.         complex arithmetic
  4359.  
  4360. A:    Ajay Shah maintains an index of free numerical software; it is
  4361.     posted periodically, and available where this FAQ list is
  4362.     archived (see question 20.40).  See also question 18.16.
  4363.  
  4364. 14.13:    I'm having trouble with a Turbo C program which crashes and says
  4365.     something like "floating point formats not linked."
  4366.  
  4367. A:    Some compilers for small machines, including Borland's (and
  4368.     Ritchie's original PDP-11 compiler), leave out certain floating
  4369.     point support if it looks like it will not be needed.  In
  4370.     particular, the non-floating-point versions of printf() and
  4371.     scanf() save space by not including code to handle %e, %f, and
  4372.     %g.  It happens that Borland's heuristics for determining
  4373.     whether the program uses floating point are insufficient, and
  4374.     the programmer must sometimes insert an extra, explicit call to
  4375.     a floating-point library routine to force loading of floating-
  4376.     point support.  (See the comp.os.msdos.programmer FAQ list for
  4377.     more information.)
  4378.  
  4379.  
  4380. Section 15. Variable-Length Argument Lists
  4381.  
  4382. 15.1:    I heard that you have to #include <stdio.h> before calling
  4383.     printf().  Why?
  4384.  
  4385. A:    So that a proper prototype for printf() will be in scope.
  4386.  
  4387.     A compiler may use a different calling sequence for functions
  4388.     which accept variable-length argument lists.  (It might do so if
  4389.     calls using variable-length argument lists were less efficient
  4390.     than those using fixed-length.)  Therefore, a prototype
  4391.     (indicating, using the ellipsis notation "...", that the
  4392.     argument list is of variable length) must be in scope whenever a
  4393.     varargs function is called, so that the compiler knows to use
  4394.     the varargs calling mechanism.
  4395.  
  4396.     References: ANSI Sec. 3.3.2.2, Sec. 4.1.6; ISO Sec. 6.3.2.2,
  4397.     Sec. 7.1.7; Rationale Sec. 3.3.2.2, Sec. 4.1.6; H&S Sec. 9.2.4
  4398.     pp. 268-9, Sec. 9.6 pp. 275-6.
  4399.  
  4400. 15.2:    How can %f be used for both float and double arguments in
  4401.     printf()?  Aren't they different types?
  4402.  
  4403. A:    In the variable-length part of a variable-length argument list,
  4404.     the "default argument promotions" apply: types char and
  4405.     short int are promoted to int, and float is promoted to double.
  4406.     (These are the same promotions that apply to function calls
  4407.     without a prototype in scope, also known as "old style" function
  4408.     calls; see question 11.3.)  Therefore, printf's %f format always
  4409.     sees a double.  (Similarly, %c always sees an int, as does %hd.)
  4410.     See also questions 12.9 and 12.13.
  4411.  
  4412.     References: ANSI Sec. 3.3.2.2; ISO Sec. 6.3.2.2; H&S Sec. 6.3.5
  4413.     p. 177, Sec. 9.4 pp. 272-3.
  4414.  
  4415. 15.3:    I had a frustrating problem which turned out to be caused by the
  4416.     line
  4417.  
  4418.         printf("%d", n);
  4419.  
  4420.     where n was actually a long int.  I thought that ANSI function
  4421.     prototypes were supposed to guard against argument type
  4422.     mismatches like this.
  4423.  
  4424. A:    When a function accepts a variable number of arguments, its
  4425.     prototype does not (and cannot) provide any information about
  4426.     the number and types of those variable arguments.  Therefore,
  4427.     the usual protections do *not* apply in the variable-length part
  4428.     of variable-length argument lists: the compiler cannot perform
  4429.     implicit conversions or (in general) warn about mismatches.
  4430.  
  4431.     See also questions 5.2, 11.3, 12.9, and 15.2.
  4432.  
  4433. 15.4:    How can I write a function that takes a variable number of
  4434.     arguments?
  4435.  
  4436. A:    Use the facilities of the <stdarg.h> header.
  4437.  
  4438.     Here is a function which concatenates an arbitrary number of
  4439.     strings into malloc'ed memory:
  4440.  
  4441.         #include <stdlib.h>        /* for malloc, NULL, size_t */
  4442.         #include <stdarg.h>        /* for va_ stuff */
  4443.         #include <string.h>        /* for strcat et al. */
  4444.  
  4445.         char *vstrcat(char *first, ...)
  4446.         {
  4447.             size_t len;
  4448.             char *retbuf;
  4449.             va_list argp;
  4450.             char *p;
  4451.  
  4452.             if(first == NULL)
  4453.                 return NULL;
  4454.  
  4455.             len = strlen(first);
  4456.  
  4457.             va_start(argp, first);
  4458.  
  4459.             while((p = va_arg(argp, char *)) != NULL)
  4460.                 len += strlen(p);
  4461.  
  4462.             va_end(argp);
  4463.  
  4464.             retbuf = malloc(len + 1);    /* +1 for trailing \0 */
  4465.  
  4466.             if(retbuf == NULL)
  4467.                 return NULL;        /* error */
  4468.  
  4469.             (void)strcpy(retbuf, first);
  4470.  
  4471.             va_start(argp, first);        /* restart for second scan */
  4472.  
  4473.             while((p = va_arg(argp, char *)) != NULL)
  4474.                 (void)strcat(retbuf, p);
  4475.  
  4476.             va_end(argp);
  4477.  
  4478.             return retbuf;
  4479.         }
  4480.  
  4481.     Usage is something like
  4482.  
  4483.         char *str = vstrcat("Hello, ", "world!", (char *)NULL);
  4484.  
  4485.     Note the cast on the last argument; see questions 5.2 and 15.3.
  4486.     (Also note that the caller must free the returned, malloc'ed
  4487.     storage.)
  4488.  
  4489.     Under a pre-ANSI compiler, rewrite the function definition
  4490.     without a prototype ("char *vstrcat(first) char *first; {"),
  4491.     include <stdio.h> rather than <stdlib.h>, add "extern
  4492.     char *malloc();", and use int instead of size_t.  You may also
  4493.     have to delete the (void) casts, and use the older varargs
  4494.     package instead of stdarg.  See also question 15.7.
  4495.  
  4496.     References: K&R2 Sec. 7.3 p. 155, Sec. B7 p. 254; ANSI Sec. 4.8;
  4497.     ISO Sec. 7.8; Rationale Sec. 4.8; H&S Sec. 11.4 pp. 296-9; CT&P
  4498.     Sec. A.3 pp. 139-141; PCS Sec. 11 pp. 184-5, Sec. 13 p. 242.
  4499.  
  4500. 15.5:    How can I write a function that takes a format string and a
  4501.     variable number of arguments, like printf(), and passes them to
  4502.     printf() to do most of the work?
  4503.  
  4504. A:    Use vprintf(), vfprintf(), or vsprintf().
  4505.  
  4506.     Here is an error() routine which prints an error message,
  4507.     preceded by the string "error: " and terminated with a newline:
  4508.  
  4509.         #include <stdio.h>
  4510.         #include <stdarg.h>
  4511.  
  4512.         void error(char *fmt, ...)
  4513.         {
  4514.             va_list argp;
  4515.             fprintf(stderr, "error: ");
  4516.             va_start(argp, fmt);
  4517.             vfprintf(stderr, fmt, argp);
  4518.             va_end(argp);
  4519.             fprintf(stderr, "\n");
  4520.         }
  4521.  
  4522.     See also question 15.7.
  4523.  
  4524.     References: K&R2 Sec. 8.3 p. 174, Sec. B1.2 p. 245; ANSI
  4525.     Secs. 4.9.6.7,4.9.6.8,4.9.6.9; ISO
  4526.     Secs. 7.9.6.7,7.9.6.8,7.9.6.9; H&S Sec. 15.12 pp. 379-80; PCS
  4527.     Sec. 11 pp. 186-7.
  4528.  
  4529. 15.6:    How can I write a function analogous to scanf(), that calls
  4530.     scanf() to do most of the work?
  4531.  
  4532. A:    Unfortunately, vscanf and the like are not standard.  You're on
  4533.     your own.
  4534.  
  4535. 15.7:    I have a pre-ANSI compiler, without <stdarg.h>.  What can I do?
  4536.  
  4537. A:    There's an older header, <varargs.h>, which offers about the
  4538.     same functionality.
  4539.  
  4540.     To rewrite the error() function from question 15.5 to use
  4541.     <varargs.h>, change the function header to:
  4542.  
  4543.         void error(va_alist)
  4544.         va_dcl
  4545.         {
  4546.             char *fmt;
  4547.  
  4548.     change the va_start line to
  4549.  
  4550.         va_start(argp);
  4551.  
  4552.     and add the line
  4553.  
  4554.         fmt = va_arg(argp, char *);
  4555.  
  4556.     between the calls to va_start and vfprintf.  (Note that there is
  4557.     no semicolon after va_dcl.)
  4558.  
  4559.     References: H&S Sec. 11.4 pp. 296-9; CT&P Sec. A.2 pp. 134-139;
  4560.     PCS Sec. 11 pp. 184-5, Sec. 13 p. 250.
  4561.  
  4562. 15.8:    How can I discover how many arguments a function was actually
  4563.     called with?
  4564.  
  4565. A:    This information is not available to a portable program.  Some
  4566.     old systems provided a nonstandard nargs() function, but its use
  4567.     was always questionable, since it typically returned the number
  4568.     of words passed, not the number of arguments.  (Structures, long
  4569.     ints, and floating point values are usually passed as several
  4570.     words.)
  4571.  
  4572.     Any function which takes a variable number of arguments must be
  4573.     able to determine *from the arguments themselves* how many of
  4574.     them there are.  printf-like functions do this by looking for
  4575.     formatting specifiers (%d and the like) in the format string
  4576.     (which is why these functions fail badly if the format string
  4577.     does not match the argument list).  Another common technique,
  4578.     applicable when the arguments are all of the same type, is to
  4579.     use a sentinel value (often 0, -1, or an appropriately-cast null
  4580.     pointer) at the end of the list (see the execl() and vstrcat()
  4581.     examples in questions 5.2 and 15.4).  Finally, if their types
  4582.     are predictable, you can pass an explicit count of the number of
  4583.     variable arguments (although it's usually a nuisance for the
  4584.     caller to generate).
  4585.  
  4586.     References: PCS Sec. 11 pp. 167-8.
  4587.  
  4588. 15.9:    My compiler isn't letting me declare a function
  4589.  
  4590.         int f(...)
  4591.         {
  4592.         }
  4593.  
  4594.     i.e. with no fixed arguments.
  4595.  
  4596. A:    Standard C requires at least one fixed argument, in part so that
  4597.     you can hand it to va_start().
  4598.  
  4599.     References: ANSI Sec. 3.5.4, Sec. 3.5.4.3, Sec. 4.8.1.1; ISO
  4600.     Sec. 6.5.4, Sec. 6.5.4.3, Sec. 7.8.1.1; H&S Sec. 9.2 p. 263.
  4601.  
  4602. 15.10:    I have a varargs function which accepts a float parameter.  Why
  4603.     isn't
  4604.  
  4605.         va_arg(argp, float)
  4606.  
  4607.     working?
  4608.  
  4609. A:    In the variable-length part of variable-length argument lists,
  4610.     the old "default argument promotions" apply: arguments of type
  4611.     float are always promoted (widened) to type double, and types
  4612.     char and short int are promoted to int.  Therefore, it is never
  4613.     correct to invoke va_arg(argp, float); instead you should always
  4614.     use va_arg(argp, double).  Similarly, use va_arg(argp, int) to
  4615.     retrieve arguments which were originally char, short, or int.
  4616.     See also questions 11.3 and 15.2.
  4617.  
  4618.     References: ANSI Sec. 3.3.2.2; ISO Sec. 6.3.2.2; Rationale
  4619.     Sec. 4.8.1.2; H&S Sec. 11.4 p. 297.
  4620.  
  4621. 15.11:    I can't get va_arg() to pull in an argument of type pointer-to-
  4622.     function.
  4623.  
  4624. A:    The type-rewriting games which the va_arg() macro typically
  4625.     plays are stymied by overly-complicated types such as pointer-to-
  4626.     function.  If you use a typedef for the function pointer type,
  4627.     however, all will be well.  See also question 1.21.
  4628.  
  4629.     References: ANSI Sec. 4.8.1.2; ISO Sec. 7.8.1.2; Rationale
  4630.     Sec. 4.8.1.2.
  4631.  
  4632. 15.12:    How can I write a function which takes a variable number of
  4633.     arguments and passes them to some other function (which takes a
  4634.     variable number of arguments)?
  4635.  
  4636. A:    In general, you cannot.  Ideally, you should provide a version
  4637.     of that other function which accepts a va_list pointer
  4638.     (analogous to vfprintf(); see question 15.5 above).  If the
  4639.     arguments must be passed directly as actual arguments, or if you
  4640.     do not have the option of rewriting the second function to
  4641.     accept a va_list (in other words, if the second, called function
  4642.     must accept a variable number of arguments, not a va_list), no
  4643.     portable solution is possible.  (The problem could perhaps be
  4644.     solved by resorting to machine-specific assembly language; see
  4645.     also question 15.13 below.)
  4646.  
  4647. 15.13:    How can I call a function with an argument list built up at run
  4648.     time?
  4649.  
  4650. A:    There is no guaranteed or portable way to do this.  If you're
  4651.     curious, ask this list's editor, who has a few wacky ideas you
  4652.     could try...
  4653.  
  4654.     Instead of an actual argument list, you might consider passing
  4655.     an array of generic (void *) pointers.  The called function can
  4656.     then step through the array, much like main() might step through
  4657.     argv.  (Obviously this works only if you have control over all
  4658.     the called functions.)
  4659.  
  4660.     (See also question 19.36.)
  4661.  
  4662.  
  4663. Section 16. Strange Problems
  4664.  
  4665. 16.3:    This program crashes before it even runs!  (When single-stepping
  4666.     with a debugger, it dies before the first statement in main().)
  4667.  
  4668. A:    You probably have one or more very large (kilobyte or more)
  4669.     local arrays.  Many systems have fixed-size stacks, and those
  4670.     which perform dynamic stack allocation automatically (e.g. Unix)
  4671.     can be confused when the stack tries to grow by a huge chunk all
  4672.     at once.  It is often better to declare large arrays with static
  4673.     duration (unless of course you need a fresh set with each
  4674.     recursive call, in which case you could dynamically allocate
  4675.     them with malloc(); see also question 1.31).
  4676.  
  4677.     (See also questions 11.12, 16.4, 16.5, and 18.4.)
  4678.  
  4679. 16.4:    I have a program that seems to run correctly, but it crashes as
  4680.     it's exiting, *after* the last statement in main().  What could
  4681.     be causing this?
  4682.  
  4683. A:    Look for a misdeclared main() (see questions 2.18 and 10.9), or
  4684.     local buffers passed to setbuf() or setvbuf(), or problems in
  4685.     cleanup functions registered by atexit().  See also questions
  4686.     7.5 and 11.16.
  4687.  
  4688.     References: CT&P Sec. 5.3 pp. 72-3.
  4689.  
  4690. 16.5:    This program runs perfectly on one machine, but I get weird
  4691.     results on another.  Stranger still, adding or removing
  4692.     debugging printouts changes the symptoms...
  4693.  
  4694. A:    Lots of things could be going wrong; here are a few of the more
  4695.     common things to check:
  4696.  
  4697.         uninitialized local variables (see also question 7.1)
  4698.  
  4699.         integer overflow, especially on 16-bit machines,
  4700.         especially of an intermediate result when doing things
  4701.         like a * b / c (see also question 3.14)
  4702.  
  4703.         undefined evaluation order (see questions 3.1 through 3.4)
  4704.  
  4705.         omitted declaration of external functions, especially
  4706.         those which return something other than int
  4707.         (see questions 1.25 and 14.2)
  4708.  
  4709.         dereferenced null pointers (see section 5)
  4710.  
  4711.         improper malloc/free use: assuming malloc'ed memory
  4712.         contains 0, assuming freed storage persists, freeing
  4713.         something twice (see also questions 7.20 and 7.19)
  4714.  
  4715.         pointer problems in general (see also question 16.8)
  4716.  
  4717.         mismatch between printf() format and arguments, especially
  4718.         trying to print long ints using %d (see question 12.9)
  4719.  
  4720.         trying to malloc(256 * 256 * sizeof(double)), especially
  4721.         on machines with limited memory (see also questions 7.16
  4722.         and 19.23)
  4723.  
  4724.         array bounds problems, especially of small, temporary
  4725.         buffers, perhaps used for constructing strings with
  4726.         sprintf() (see also questions 7.1 and 12.21)
  4727.  
  4728.         invalid assumptions about the mapping of typedefs,
  4729.         especially size_t
  4730.  
  4731.         floating point problems (see questions 14.1 and 14.4)
  4732.  
  4733.         anything you thought was a clever exploitation of the way
  4734.         you believe code is generated for your specific system
  4735.  
  4736.     Proper use of function prototypes can catch several of these
  4737.     problems; lint would catch several more.  See also questions
  4738.     16.3, 16.4, and 18.4.
  4739.  
  4740. 16.6:    Why does this code:
  4741.  
  4742.         char *p = "hello, world!";
  4743.         p[0] = 'H';
  4744.  
  4745.     crash?
  4746.  
  4747. A:    String literals are not necessarily modifiable, except (in
  4748.     effect) when they are used as array initializers.  Try
  4749.  
  4750.         char a[] = "hello, world!";
  4751.  
  4752.     See also question 1.32.
  4753.  
  4754.     References: ANSI Sec. 3.1.4; ISO Sec. 6.1.4; H&S Sec. 2.7.4 pp.
  4755.     31-2.
  4756.  
  4757. 16.8:    What do "Segmentation violation" and "Bus error" mean?
  4758.  
  4759. A:    These generally mean that your program tried to access memory it
  4760.     shouldn't have, invariably as a result of improper pointer use.
  4761.     Likely causes are inadvertent use of null pointers (see also
  4762.     questions 5.2 and 5.20) or uninitialized, misaligned, or
  4763.     otherwise improperly allocated pointers (see questions 7.1 and
  4764.     7.2); corruption of the malloc arena (see question 7.19); and
  4765.     mismatched function arguments, especially involving pointers;
  4766.     two possibilities are scanf() (see question 12.12) and fprintf()
  4767.     (make sure it receives its first FILE * argument).
  4768.  
  4769.     See also questions 16.3 and 16.4.
  4770.  
  4771.  
  4772. Section 17. Style
  4773.  
  4774. 17.1:    What's the best style for code layout in C?
  4775.  
  4776. A:    K&R, while providing the example most often copied, also supply
  4777.     a good excuse for disregarding it:
  4778.  
  4779.         The position of braces is less important,
  4780.         although people hold passionate beliefs.
  4781.         We have chosen one of several popular styles.
  4782.         Pick a style that suits you, then use it
  4783.         consistently.
  4784.  
  4785.     It is more important that the layout chosen be consistent (with
  4786.     itself, and with nearby or common code) than that it be
  4787.     "perfect."  If your coding environment (i.e. local custom or
  4788.     company policy) does not suggest a style, and you don't feel
  4789.     like inventing your own, just copy K&R.  (The tradeoffs between
  4790.     various indenting and brace placement options can be
  4791.     exhaustively and minutely examined, but don't warrant repetition
  4792.     here.  See also the Indian Hill Style Guide.)
  4793.  
  4794.     The elusive quality of "good style" involves much more than mere
  4795.     code layout details; don't spend time on formatting to the
  4796.     exclusion of more substantive code quality issues.
  4797.  
  4798.     See also question 10.6.
  4799.  
  4800.     References: K&R1 Sec. 1.2 p. 10; K&R2 Sec. 1.2 p. 10.
  4801.  
  4802. 17.3:    Here's a neat trick for checking whether two strings are equal:
  4803.  
  4804.         if(!strcmp(s1, s2))
  4805.  
  4806.     Is this good style?
  4807.  
  4808. A:    It is not particularly good style, although it is a popular
  4809.     idiom.  The test succeeds if the two strings are equal, but the
  4810.     use of ! ("not") suggests that it tests for inequality.
  4811.  
  4812.     A better option is to use a macro:
  4813.  
  4814.         #define Streq(s1, s2) (strcmp((s1), (s2)) == 0)
  4815.  
  4816.     Opinions on code style, like those on religion, can be debated
  4817.     endlessly.  Though good style is a worthy goal, and can usually
  4818.     be recognized, it cannot be rigorously codified.  See also
  4819.     question 17.10.
  4820.  
  4821. 17.4:    Why do some people write if(0 == x) instead of if(x == 0)?
  4822.  
  4823. A:    It's a trick to guard against the common error of writing
  4824.  
  4825.         if(x = 0)
  4826.  
  4827.     If you're in the habit of writing the constant before the ==,
  4828.     the compiler will complain if you accidentally type
  4829.  
  4830.         if(0 = x)
  4831.  
  4832.     Evidently it can be easier to remember to reverse the test than
  4833.     it is to remember to type the doubled = sign.
  4834.  
  4835.     References: H&S Sec. 7.6.5 pp. 209-10.
  4836.  
  4837. 17.5:    I came across some code that puts a (void) cast before each call
  4838.     to printf().  Why?
  4839.  
  4840. A:    printf() does return a value, though few programs bother to
  4841.     check the return values from each call.  Since some compilers
  4842.     (and lint) will warn about discarded return values, an explicit
  4843.     cast to (void) is a way of saying "Yes, I've decided to ignore
  4844.     the return value from this call, but please continue to warn me
  4845.     about other (perhaps inadvertently) ignored return values."
  4846.     It's also common to use void casts on calls to strcpy() and
  4847.     strcat(), since the return value is never surprising.
  4848.  
  4849.     References: K&R2 Sec. A6.7 p. 199; Rationale Sec. 3.3.4; H&S
  4850.     Sec. 6.2.9 p. 172, Sec. 7.13 pp. 229-30.
  4851.  
  4852. 17.8:    What is "Hungarian Notation"?  Is it worthwhile?
  4853.  
  4854. A:    Hungarian Notation is a naming convention, invented by Charles
  4855.     Simonyi, which encodes things about a variable's type (and
  4856.     perhaps its intended use) in its name.  It is well-loved in some
  4857.     circles and roundly castigated in others.  Its chief advantage
  4858.     is that it makes a variable's type or intended use obvious from
  4859.     its name; its chief disadvantage is that type information is not
  4860.     necessarily a worthwhile thing to carry around in the name of a
  4861.     variable.
  4862.  
  4863.     References: Simonyi and Heller, "The Hungarian Revolution" .
  4864.  
  4865. 17.9:    Where can I get the "Indian Hill Style Guide" and other coding
  4866.     standards?
  4867.  
  4868. A:    Various documents are available for anonymous ftp from:
  4869.  
  4870.         Site:            File or directory:
  4871.  
  4872.         cs.washington.edu    pub/cstyle.tar.Z
  4873.                     (the updated Indian Hill guide)
  4874.  
  4875.         ftp.cs.toronto.edu    doc/programming
  4876.                     (including Henry Spencer's
  4877.                     "10 Commandments for C Programmers")
  4878.  
  4879.         ftp.cs.umd.edu        pub/style-guide
  4880.  
  4881.     You may also be interested in the books _The Elements of
  4882.     Programming Style_, _Plum Hall Programming Guidelines_, and _C
  4883.     Style: Standards and Guidelines_; see the Bibliography.  (The
  4884.     _Standards and Guidelines_ book is not in fact a style guide,
  4885.     but a set of guidelines on selecting and creating style guides.)
  4886.  
  4887.     See also question 18.9.
  4888.  
  4889. 17.10:    Some people say that goto's are evil and that I should never use
  4890.     them.  Isn't that a bit extreme?
  4891.  
  4892. A:    Programming style, like writing style, is somewhat of an art and
  4893.     cannot be codified by inflexible rules, although discussions
  4894.     about style often seem to center exclusively around such rules.
  4895.  
  4896.     In the case of the goto statement, it has long been observed
  4897.     that unfettered use of goto's quickly leads to unmaintainable
  4898.     spaghetti code.  However, a simple, unthinking ban on the goto
  4899.     statement does not necessarily lead immediately to beautiful
  4900.     programming: an unstructured programmer is just as capable of
  4901.     constructing a Byzantine tangle without using any goto's
  4902.     (perhaps substituting oddly-nested loops and Boolean control
  4903.     variables, instead).
  4904.  
  4905.     Most observations or "rules" about programming style usually
  4906.     work better as guidelines than rules, and work much better if
  4907.     programmers understand what the guidelines are trying to
  4908.     accomplish.  Blindly avoiding certain constructs or following
  4909.     rules without understanding them can lead to just as many
  4910.     problems as the rules were supposed to avert.
  4911.  
  4912.     Furthermore, many opinions on programming style are just that:
  4913.     opinions.  It's usually futile to get dragged into "style wars,"
  4914.     because on certain issues (such as those referred to in
  4915.     questions 9.2, 5.3, 5.9, and 10.7), opponents can never seem to
  4916.     agree, or agree to disagree, or stop arguing.
  4917.  
  4918.  
  4919. Section 18. Tools and Resources
  4920.  
  4921. 18.1:    I need:                 A:    Look for programs (see also
  4922.                     question 18.16) named:
  4923.  
  4924.     a C cross-reference        cflow, cxref, calls, cscope,
  4925.     generator            xscope, or ixfw
  4926.  
  4927.     a C beautifier/pretty-        cb, indent, GNU indent, or
  4928.     printer                vgrind
  4929.  
  4930.     a revision control or        RCS or SCCS
  4931.     configuration management
  4932.     tool
  4933.  
  4934.     a C source obfuscator        obfus, shroud, or opqcp
  4935.     (shrouder)
  4936.  
  4937.     a "make" dependency        makedepend, or try cc -M or
  4938.     generator            cpp -M
  4939.  
  4940.     tools to compute code        ccount, Metre, lcount, or
  4941.     metrics                csize, or see URL
  4942.                     http://www.qucis.queensu.ca:1999/Software-
  4943.                     Engineering/Cmetrics.html ;
  4944.                     there is also a package sold
  4945.                     by McCabe and Associates
  4946.  
  4947.     a C lines-of-source        this can be done very
  4948.     counter                crudely with the standard
  4949.                     Unix utility wc, and
  4950.                     considerably better with
  4951.                     grep -c ";"
  4952.  
  4953.     a prototype generator        see question 11.31
  4954.  
  4955.     a tool to track down
  4956.     malloc problems            see question 18.2
  4957.  
  4958.     a "selective" C
  4959.     preprocessor            see question 10.18
  4960.  
  4961.     language translation        see questions 11.31 and
  4962.     tools                 20.26
  4963.  
  4964.     C verifiers (lint)        see question 18.7
  4965.  
  4966.     a C compiler!            see question 18.3
  4967.  
  4968.     (This list of tools is by no means complete; if you know of tools
  4969.     not mentioned, you're welcome to contact this list's maintainer.)
  4970.  
  4971.     Other lists of tools, and discussion about them, can be found in
  4972.     the Usenet newsgroups comp.compilers and comp.software-eng .
  4973.  
  4974.     See also questions 18.16 and 18.3.
  4975.  
  4976. 18.2:    How can I track down these pesky malloc problems?
  4977.  
  4978. A:    A number of debugging packages exist to help track down malloc
  4979.     problems; one popular one is Conor P. Cahill's "dbmalloc,"
  4980.     posted to comp.sources.misc in 1992, volume 32.  Others are
  4981.     "leak," available in volume 27 of the comp.sources.unix
  4982.     archives; JMalloc.c and JMalloc.h in the "Snippets" collection;
  4983.     and MEMDEBUG from ftp.crpht.lu in pub/sources/memdebug .  See
  4984.     also question 18.16.
  4985.  
  4986.     A number of commercial debugging tools exist, and can be
  4987.     invaluable in tracking down malloc-related and other stubborn
  4988.     problems:
  4989.  
  4990.         Bounds-Checker for DOS, from Nu-Mega Technologies,
  4991.         P.O. Box 7780, Nashua, NH 03060-7780, USA, 603-889-2386.
  4992.  
  4993.         CodeCenter (formerly Saber-C) from Centerline Software
  4994.         (formerly Saber), 10 Fawcett Street, Cambridge, MA
  4995.         02138-1110, USA, 617-498-3000.
  4996.  
  4997.         Insight, from ParaSoft Corporation, 2500 E. Foothill
  4998.         Blvd., Pasadena, CA 91107, USA, 818-792-9941,
  4999.         insight@parasoft.com .
  5000.  
  5001.         Purify, from Pure Software, 1309 S. Mary Ave., Sunnyvale,
  5002.         CA 94087, USA, 800-224-7873, info-home@pure.com .
  5003.  
  5004.         SENTINEL, from AIB Software, 46030 Manekin Plaza, Dulles,
  5005.         VA 20166, USA, 703-430-9247, 800-296-3000, info@aib.com .
  5006.  
  5007. 18.3:    What's a free or cheap C compiler I can use?
  5008.  
  5009. A:    A popular and high-quality free C compiler is the FSF's GNU C
  5010.     compiler, or gcc.  It is available by anonymous ftp from
  5011.     prep.ai.mit.edu in directory pub/gnu, or at several other FSF
  5012.     archive sites.  An MS-DOS port, djgpp, is also available; it can
  5013.     be found in the Simtel and Oakland archives and probably many
  5014.     others, usually in a directory like pub/msdos/djgpp/ or
  5015.     simtel/msdos/djgpp/.
  5016.  
  5017.     There is a shareware compiler called PCC, available as
  5018.     PCC12C.ZIP .
  5019.  
  5020.     A very inexpensive MS-DOS compiler is Power C from Mix Software,
  5021.     1132 Commerce Drive, Richardson, TX 75801, USA, 214-783-6001.
  5022.  
  5023.     Another recently-developed compiler is lcc, available for
  5024.     anonymous ftp from ftp.cs.princeton.edu in pub/lcc.
  5025.  
  5026.     Archives associated with comp.compilers contain a great deal of
  5027.     information about available compilers, interpreters, grammars,
  5028.     etc. (for many languages).  The comp.compilers archives
  5029.     (including an FAQ list), maintained by the moderator, John R.
  5030.     Levine, are at iecc.com .  A list of available compilers and
  5031.     related resources, maintained by Mark Hopkins, Steven Robenalt,
  5032.     and David Muir Sharnoff, is at ftp.idiom.com in pub/compilers-
  5033.     list/.  (See also the comp.compilers directory in the
  5034.     news.answers archives at rtfm.mit.edu and ftp.uu.net; see
  5035.     question 20.40.)
  5036.  
  5037.     See also question 18.16.
  5038.  
  5039. 18.4:    I just typed in this program, and it's acting strangely.  Can
  5040.     you see anything wrong with it?
  5041.  
  5042. A:    See if you can run lint first (perhaps with the -a, -c, -h, -p
  5043.     or other options).  Many C compilers are really only half-
  5044.     compilers, electing not to diagnose numerous source code
  5045.     difficulties which would not actively preclude code generation.
  5046.  
  5047.     See also questions 16.5 and 16.8.
  5048.  
  5049.     References: Ian Darwin, _Checking C Programs with lint_ .
  5050.  
  5051. 18.5:    How can I shut off the "warning: possible pointer alignment
  5052.     problem" message which lint gives me for each call to malloc()?
  5053.  
  5054. A:    The problem is that traditional versions of lint do not know,
  5055.     and cannot be told, that malloc() "returns a pointer to space
  5056.     suitably aligned for storage of any type of object."  It is
  5057.     possible to provide a pseudoimplementation of malloc(), using a
  5058.     #define inside of #ifdef lint, which effectively shuts this
  5059.     warning off, but a simpleminded definition will also suppress
  5060.     meaningful messages about truly incorrect invocations.  It may
  5061.     be easier simply to ignore the message, perhaps in an automated
  5062.     way with grep -v.  (But don't get in the habit of ignoring too
  5063.     many lint messages, otherwise one day you'll overlook a
  5064.     significant one.)
  5065.  
  5066. 18.7:    Where can I get an ANSI-compatible lint?
  5067.  
  5068. A:    Products called PC-Lint and FlexeLint (in "shrouded source
  5069.     form," for compilation on 'most any system) are available from
  5070.  
  5071.         Gimpel Software
  5072.         3207 Hogarth Lane
  5073.         Collegeville, PA  19426  USA
  5074.         (+1) 610 584 4261
  5075.         gimpel@netaxs.com
  5076.  
  5077.     The Unix System V release 4 lint is ANSI-compatible, and is
  5078.     available separately (bundled with other C tools) from UNIX
  5079.     Support Labs or from System V resellers.
  5080.  
  5081.     Another ANSI-compatible lint (which can also perform higher-
  5082.     level formal verification) is LCLint, available via anonymous
  5083.     ftp from larch.lcs.mit.edu in pub/Larch/lclint/.
  5084.  
  5085.     In the absence of lint, many modern compilers do attempt to
  5086.     diagnose almost as many problems as lint does.
  5087.  
  5088. 18.8:    Don't ANSI function prototypes render lint obsolete?
  5089.  
  5090. A:    Not really.  First of all, prototypes work only if they are
  5091.     present and correct; an inadvertently incorrect prototype is
  5092.     worse than useless.  Secondly, lint checks consistency across
  5093.     multiple source files, and checks data declarations as well as
  5094.     functions.  Finally, an independent program like lint will
  5095.     probably always be more scrupulous at enforcing compatible,
  5096.     portable coding practices than will any particular,
  5097.     implementation-specific, feature- and extension-laden compiler.
  5098.  
  5099.     If you do want to use function prototypes instead of lint for
  5100.     cross-file consistency checking, make sure that you set the
  5101.     prototypes up correctly in header files.  See questions 1.7 and
  5102.     10.6.
  5103.  
  5104. 18.9:    Are there any C tutorials or other resources on the net?
  5105.  
  5106. A:    There are several of them:
  5107.  
  5108.     "Notes for C programmers," by Christopher Sawtell, are
  5109.     available from svr-ftp.eng.cam.ac.uk in misc/sawtell_C.shar and
  5110.     garbo.uwasa.fi in /pc/c-lang/c-lesson.zip .
  5111.  
  5112.     Tim Love's "C for Programmers" is available by ftp from svr-
  5113.     ftp.eng.cam.ac.uk in the misc directory.  An html version is at
  5114.     http://club.eng.cam.ac.uk/help/tpl/languages/C/teaching_C/teaching_C.html .
  5115.  
  5116.     The Coronado Enterprises C tutorials are available on Simtel
  5117.     mirrors in pub/msdos/c/.
  5118.  
  5119.     Rick Rowe has a tutorial which is available from ftp.netcom.com
  5120.     as pub/rowe/tutorde.zip or ftp.wustl.edu as
  5121.     pub/MSDOS_UPLOADS/programming/c_language/ctutorde.zip .
  5122.  
  5123.     There is evidently a web-based course at
  5124.     http://www.strath.ac.uk/CC/Courses/CCourse/CCourse.html .
  5125.  
  5126.     Finally, on some Unix machines you can try typing learn c at the
  5127.     shell prompt.
  5128.  
  5129.     [Disclaimer: I have not reviewed these tutorials; I have heard
  5130.     that at least one of them contains a number of errors.  Also,
  5131.     this sort of information rapidly becomes out-of-date; these
  5132.     addresses may not work by the time you read this and try them.]
  5133.  
  5134.     Several of these tutorials, plus a great deal of other
  5135.     information about C, are accessible via the web at
  5136.     http://www.lysator.liu.se/c/index.html .
  5137.  
  5138.     Vinit Carpenter maintains a list of resources for learning C and
  5139.     C++; it is posted to comp.lang.c and comp.lang.c++, and archived
  5140.     where this FAQ list is (see question 20.40), or on the web at
  5141.     http://vinny.csd.mu.edu/ .
  5142.  
  5143.     See also question 18.10 below.
  5144.  
  5145. 18.10:    What's a good book for learning C?
  5146.  
  5147. A:    There are far too many books on C to list here; it's impossible
  5148.     to rate them all.  Many people believe that the best one was
  5149.     also the first: _The C Programming Language_, by Kernighan and
  5150.     Ritchie ("K&R," now in its second edition).  Opinions vary on
  5151.     K&R's suitability as an initial programming text: many of us did
  5152.     learn C from it, and learned it well; some, however, feel that
  5153.     it is a bit too clinical as a first tutorial for those without
  5154.     much programming background.
  5155.  
  5156.     An excellent reference manual is _C: A Reference Manual_, by
  5157.     Samuel P. Harbison and Guy L. Steele, now in its fourth edition.
  5158.  
  5159.     Though not suitable for learning C from scratch, this FAQ list
  5160.     has been published in book form; see the Bibliography.
  5161.  
  5162.     Mitch Wright maintains an annotated bibliography of C and Unix
  5163.     books; it is available for anonymous ftp from ftp.rahul.net in
  5164.     directory pub/mitch/YABL/.
  5165.  
  5166.     This FAQ list's editor maintains a collection of previous
  5167.     answers to this question, which is available upon request.  See
  5168.     also question 18.9 above.
  5169.  
  5170. 18.13:    Where can I find the sources of the standard C libraries?
  5171.  
  5172. A:    One source (though not public domain) is _The Standard C
  5173.     Library_, by P.J. Plauger (see the Bibliography).
  5174.     Implementations of all or part of the C library have been
  5175.     written and are readily available as part of the netBSD and GNU
  5176.     (also Linux) projects.  See also question 18.16.
  5177.  
  5178. 18.14:    I need code to parse and evaluate expressions.
  5179.  
  5180. A:    Two available packages are "defunc," posted to comp.sources.misc
  5181.     in December, 1993 (V41 i32,33), to alt.sources in January, 1994,
  5182.     and available from sunsite.unc.edu in
  5183.     pub/packages/development/libraries/defunc-1.3.tar.Z, and
  5184.     "parse," at lamont.ldgo.columbia.edu.  Other options include the
  5185.     S-Lang interpreter, available via anonymous ftp from
  5186.     amy.tch.harvard.edu in pub/slang, and the shareware Cmm ("C-
  5187.     minus-minus" or "C minus the hard stuff").  See also question
  5188.     18.16.
  5189.  
  5190.     There is also some parsing/evaluation code in _Software
  5191.     Solutions in C_ (chapter 12, pp. 235-55).
  5192.  
  5193. 18.15:    Where can I get a BNF or YACC grammar for C?
  5194.  
  5195. A:    The definitive grammar is of course the one in the ANSI
  5196.     standard; see question 11.2.  Another grammar (along with one
  5197.     for C++) by Jim Roskind is in pub/c++grammar1.1.tar.Z at
  5198.     ics.uci.edu .  A fleshed-out, working instance of the ANSI
  5199.     grammar (due to Jeff Lee) is on ftp.uu.net (see question 18.16)
  5200.     in usenet/net.sources/ansi.c.grammar.Z (including a companion
  5201.     lexer).  The FSF's GNU C compiler contains a grammar, as does
  5202.     the appendix to K&R2.
  5203.  
  5204.     The comp.compilers archives contain more information about
  5205.     grammars; see question 18.3.
  5206.  
  5207.     References: K&R1 Sec. A18 pp. 214-219; K&R2 Sec. A13 pp. 234-
  5208.     239; ANSI Sec. A.2; ISO Sec. B.2; H&S pp. 423-435 Appendix B.
  5209.  
  5210. 18.15a: Does anyone have a C compiler test suite I can use?
  5211.  
  5212. A:    Plum Hall (formerly in Cardiff, NJ; now in Hawaii) sells one;
  5213.     another package is Ronald Guilmette's RoadTest(tm) Compiler Test
  5214.     Suites (ftp to netcom.com, pub/rfg/roadtest/announce.txt for
  5215.     information).  The FSF's GNU C (gcc) distribution includes a c-
  5216.     torture-test which checks a number of common problems with
  5217.     compilers.  Kahan's paranoia test, found in netlib/paranoia on
  5218.     netlib.att.com, strenuously tests a C implementation's floating
  5219.     point capabilities.
  5220.  
  5221. 18.16:    Where and how can I get copies of all these freely distributable
  5222.     programs?
  5223.  
  5224. A:    As the number of available programs, the number of publicly
  5225.     accessible archive sites, and the number of people trying to
  5226.     access them all grow, this question becomes both easier and more
  5227.     difficult to answer.
  5228.  
  5229.     There are a number of large, public-spirited archive sites out
  5230.     there, such as ftp.uu.net, archive.umich.edu, oak.oakland.edu,
  5231.     sumex-aim.stanford.edu, and wuarchive.wustl.edu, which have huge
  5232.     amounts of software and other information all freely available.
  5233.     For the FSF's GNU project, the central distribution site is
  5234.     prep.ai.mit.edu .  These well-known sites tend to be extremely
  5235.     busy and hard to reach, but there are also numerous "mirror"
  5236.     sites which try to spread the load around.
  5237.  
  5238.     On the connected Internet, the traditional way to retrieve files
  5239.     from an archive site is with anonymous ftp.  For those without
  5240.     ftp access, there are also several ftp-by-mail servers in
  5241.     operation.  More and more, the world-wide web (WWW) is being
  5242.     used to announce, index, and even transfer large data files.
  5243.     There are probably yet newer access methods, too.
  5244.  
  5245.     Those are some of the easy parts of the question to answer.  The
  5246.     hard part is in the details -- this article cannot begin to
  5247.     track or list all of the available archive sites or all of the
  5248.     various ways of accessing them.  If you have access to the net
  5249.     at all, you probably have access to more up-to-date information
  5250.     about active sites and useful access methods than this FAQ list
  5251.     does.
  5252.  
  5253.     The other easy-and-hard aspect of the question, of course, is
  5254.     simply *finding* which site has what you're looking for.  There
  5255.     is a tremendous amount of work going on in this area, and there
  5256.     are probably new indexing services springing up every day.  One
  5257.     of the first was "archie": for any program or resource available
  5258.     on the net, if you know its name, an archie server can usually
  5259.     tell you which anonymous ftp sites have it.  Your system may
  5260.     have an archie command, or you can send the mail message "help"
  5261.     to archie@archie.cs.mcgill.ca for information.
  5262.  
  5263.     If you have access to Usenet, see the regular postings in the
  5264.     comp.sources.unix and comp.sources.misc newsgroups, which
  5265.     describe the archiving policies for those groups and how to
  5266.     access their archives.  The comp.archives newsgroup contains
  5267.     numerous announcements of anonymous ftp availability of various
  5268.     items.  Finally, the newsgroup comp.sources.wanted is generally
  5269.     a more appropriate place to post queries for source
  5270.     availability, but check *its* FAQ list, "How to find sources,"
  5271.     before posting there.
  5272.  
  5273.     See also question 14.12.
  5274.  
  5275. Section 19. System Dependencies
  5276.  
  5277. 19.1:    How can I read a single character from the keyboard without
  5278.     waiting for the RETURN key?  How can I stop characters from
  5279.     being echoed on the screen as they're typed?
  5280.  
  5281. A:    Alas, there is no standard or portable way to do these things in
  5282.     C.  Concepts such as screens and keyboards are not even
  5283.     mentioned in the Standard, which deals only with simple I/O
  5284.     "streams" of characters.
  5285.  
  5286.     At some level, interactive keyboard input is usually collected
  5287.     and presented to the requesting program a line at a time.  This
  5288.     gives the operating system a chance to support input line
  5289.     editing (backspace/delete/rubout, etc.) in a consistent way,
  5290.     without requiring that it be built into every program.  Only
  5291.     when the user is satisfied and presses the RETURN key (or
  5292.     equivalent) is the line made available to the calling program.
  5293.     Even if the calling program appears to be reading input a
  5294.     character at a time (with getchar() or the like), the first call
  5295.     blocks until the user has typed an entire line, at which point
  5296.     potentially many characters become available and many character
  5297.     requests (e.g. getchar() calls) are satisfied in quick
  5298.     succession.
  5299.  
  5300.     When a program wants to read each character immediately as it
  5301.     arrives, its course of action will depend on where in the input
  5302.     stream the line collection is happening and how it can be
  5303.     disabled.  Under some systems (e.g. MS-DOS, VMS in some modes),
  5304.     a program can use a different or modified set of OS-level input
  5305.     calls to bypass line-at-a-time input processing.  Under other
  5306.     systems (e.g. Unix, VMS in other modes), the part of the
  5307.     operating system responsible for serial input (often called the
  5308.     "terminal driver") must be placed in a mode which turns off line-
  5309.     at-a-time processing, after which all calls to the usual input
  5310.     routines (e.g. read(), getchar(), etc.) will return characters
  5311.     immediately.  Finally, a few systems (particularly older, batch-
  5312.     oriented mainframes) perform input processing in peripheral
  5313.     processors which cannot be told to do anything other than line-
  5314.     at-a-time input.
  5315.  
  5316.     Therefore, when you need to do character-at-a-time input (or
  5317.     disable keyboard echo, which is an analogous problem), you will
  5318.     have to use a technique specific to the system you're using,
  5319.     assuming it provides one.  Since comp.lang.c is oriented towards
  5320.     topics that C does deal with, you will usually get better
  5321.     answers to these questions by referring to a system-specific
  5322.     newsgroup such as comp.unix.questions or
  5323.     comp.os.msdos.programmer, and to the FAQ lists for these groups.
  5324.     Note that the answers are often not unique even across different
  5325.     variants of a system; bear in mind when answering system-
  5326.     specific questions that the answer that applies to your system
  5327.     may not apply to everyone else's.
  5328.  
  5329.     However, since these questions are frequently asked here, here
  5330.     are brief answers for some common situations.
  5331.  
  5332.     Some versions of curses have functions called cbreak(),
  5333.     noecho(), and getch() which do what you want.  If you're
  5334.     specifically trying to read a short password without echo, you
  5335.     might try getpass().  Under Unix, you can use ioctl() to play
  5336.     with the terminal driver modes (CBREAK or RAW under "classic"
  5337.     versions; ICANON, c_cc[VMIN] and c_cc[VTIME] under System V or
  5338.     POSIX systems; ECHO under all versions), or in a pinch, system()
  5339.     and the stty command.  (For more information, see <sgtty.h> and
  5340.     tty(4) under classic versions, <termio.h> and termio(4) under
  5341.     System V, or <termios.h> and termios(4) under POSIX.)  Under MS-
  5342.     DOS, use getch() or getche(), or the corresponding BIOS
  5343.     interrupts.  Under VMS, try the Screen Management (SMG$)
  5344.     routines, or curses, or issue low-level $QIO's with the
  5345.     IO$_READVBLK function code (and perhaps IO$M_NOECHO, and others)
  5346.     to ask for one character at a time.  (It's also possible to set
  5347.     character-at-a-time or "pass through" modes in the VMS terminal
  5348.     driver.)  Under other operating systems, you're on your own.
  5349.  
  5350.     (As an aside, note that simply using setbuf() or setvbuf() to
  5351.     set stdin to unbuffered will *not* generally serve to allow
  5352.     character-at-a-time input.)
  5353.  
  5354.     If you're trying to write a portable program, a good approach is
  5355.     to define your own suite of three functions to (1) set the
  5356.     terminal driver or input system into character-at-a-time mode
  5357.     (if necessary), (2) get characters, and (3) return the terminal
  5358.     driver to its initial state when the program is finished.
  5359.     (Ideally, such a set of functions might be part of the C
  5360.     Standard, some day.)  The extended versions of this FAQ list
  5361.     (see question 20.40) contain examples of such functions for
  5362.     several popular systems.
  5363.  
  5364.     See also question 19.2.
  5365.  
  5366.     References: PCS Sec. 10 pp. 128-9, Sec. 10.1 pp. 130-1; POSIX
  5367.     Sec. 7.
  5368.  
  5369. 19.2:    How can I find out if there are characters available for reading
  5370.     (and if so, how many)?  Alternatively, how can I do a read that
  5371.     will not block if there are no characters available?
  5372.  
  5373. A:    These, too, are entirely operating-system-specific.  Some
  5374.     versions of curses have a nodelay() function.  Depending on your
  5375.     system, you may also be able to use "nonblocking I/O", or a
  5376.     system call named "select" or "poll", or the FIONREAD ioctl, or
  5377.     c_cc[VTIME], or kbhit(), or rdchk(), or the O_NDELAY option to
  5378.     open() or fcntl().  See also question 19.1.
  5379.  
  5380. 19.3:    How can I display a percentage-done indication that updates
  5381.     itself in place, or show one of those "twirling baton" progress
  5382.     indicators?
  5383.  
  5384. A:    These simple things, at least, you can do fairly portably.
  5385.     Printing the character '\r' will usually give you a carriage
  5386.     return without a line feed, so that you can overwrite the
  5387.     current line.  The character '\b' is a backspace, and will
  5388.     usually move the cursor one position to the left.
  5389.  
  5390.     References: ANSI Sec. 2.2.2; ISO Sec. 5.2.2.
  5391.  
  5392. 19.4:    How can I clear the screen?
  5393.     How can I print things in inverse video?
  5394.     How can I move the cursor to a specific x, y position?
  5395.  
  5396. A:    Such things depend on the terminal type (or display) you're
  5397.     using.  You will have to use a library such as termcap,
  5398.     terminfo, or curses, or some system-specific routines, to
  5399.     perform these operations.
  5400.  
  5401.     For clearing the screen, a halfway portable solution is to print
  5402.     a form-feed character ('\f'), which will cause some displays to
  5403.     clear.  Even more portable would be to print enough newlines to
  5404.     scroll everything away.  As a last resort, you could use
  5405.     system() (see question 19.27) to invoke an operating system
  5406.     clear-screen command.
  5407.  
  5408.     References: PCS Sec. 5.1.4 pp. 54-60, Sec. 5.1.5 pp. 60-62.
  5409.  
  5410. 19.5:    How do I read the arrow keys?  What about function keys?
  5411.  
  5412. A:    Terminfo, some versions of termcap, and some versions of curses
  5413.     have support for these non-ASCII keys.  Typically, a special key
  5414.     sends a multicharacter sequence (usually beginning with ESC,
  5415.     '\033'); parsing these can be tricky.  (curses will do the
  5416.     parsing for you, if you call keypad() first.)
  5417.  
  5418.     Under MS-DOS, if you receive a character with value 0 (*not*
  5419.     '0'!) while reading the keyboard, it's a flag indicating that
  5420.     the next character read will be a code indicating a special key.
  5421.     See any DOS programming guide for lists of keyboard codes.
  5422.     (Very briefly: the up, left, right, and down arrow keys are 72,
  5423.     75, 77, and 80, and the function keys are 59 through 68.)
  5424.  
  5425.     References: PCS Sec. 5.1.4 pp. 56-7.
  5426.  
  5427. 19.6:    How do I read the mouse?
  5428.  
  5429. A:    Consult your system documentation, or ask on an appropriate
  5430.     system-specific newsgroup (but check its FAQ list first).  Mouse
  5431.     handling is completely different under the X window system, MS-
  5432.     DOS, the Macintosh, and probably every other system.
  5433.  
  5434.     References: PCS Sec. 5.5 pp. 78-80.
  5435.  
  5436. 19.7:    How can I do serial ("comm") port I/O?
  5437.  
  5438. A:    It's system-dependent.  Under Unix, you typically open, read,
  5439.     and write a device file in /dev, and use the facilities of the
  5440.     terminal driver to adjust its characteristics.  (See also
  5441.     questions 19.1 and 19.2.)  Under MS-DOS, you can use the
  5442.     predefined stream stdaux, or a special file like COM1, or some
  5443.     primitive BIOS interrupts, or (if you require decent
  5444.     performance) any number of interrupt-driven serial I/O packages.
  5445.     Several netters recommend the book _C Programmer's Guide to
  5446.     Serial Communications_, by Joe Campbell.
  5447.  
  5448. 19.8:    How can I direct output to the printer?
  5449.  
  5450. A:    Under Unix, either use popen() (see question 19.30) to write to
  5451.     the lp or lpr program, or perhaps open a special file like
  5452.     /dev/lp.  Under MS-DOS, write to the (nonstandard) predefined
  5453.     stdio stream stdprn, or open the special files PRN or LPT1.
  5454.  
  5455.     References: PCS Sec. 5.3 pp. 72-74.
  5456.  
  5457. 19.9:    How do I send escape sequences to control a terminal or other
  5458.     device?
  5459.  
  5460. A:    If you can figure out how to send characters to the device at
  5461.     all (see question 19.8 above), it's easy enough to send escape
  5462.     sequences.  In ASCII, the ESC code is 033 (27 decimal), so code
  5463.     like
  5464.  
  5465.         fprintf(ofd, "\033[J");
  5466.  
  5467.     sends the sequence ESC [ J .
  5468.  
  5469. 19.10:    How can I do graphics?
  5470.  
  5471. A:    Once upon a time, Unix had a fairly nice little set of device-
  5472.     independent plot routines described in plot(3) and plot(5), but
  5473.     they've largely fallen into disuse.
  5474.  
  5475.     If you're programming for MS-DOS, you'll probably want to use
  5476.     libraries conforming to the VESA or BGI standards.
  5477.  
  5478.     If you're trying to talk to a particular plotter, making it draw
  5479.     is usually a matter of sending it the appropriate escape
  5480.     sequences; see also question 19.9.  The vendor may supply a C-
  5481.     callable library, or you may be able to find one on the net.
  5482.  
  5483.  
  5484.     If you're programming for a particular window system (Macintosh,
  5485.     X windows, Microsoft Windows), you will use its facilities; see
  5486.     the relevant documentation or newsgroup or FAQ list.
  5487.  
  5488.     References: PCS Sec. 5.4 pp. 75-77.
  5489.  
  5490. 19.11:    How can I check whether a file exists?  I want to warn the user
  5491.     if a requested input file is missing.
  5492.  
  5493. A:    It's surprisingly difficult to make this determination reliably
  5494.     and portably.  Any test you make can be invalidated if the file
  5495.     is created or deleted (i.e. by some other process) between the
  5496.     time you make the test and the time you try to open the file.
  5497.  
  5498.     Three possible test routines are stat(), access(), and fopen().
  5499.     (To make an approximate test for file existence with fopen(),
  5500.     just open for reading and close immediately.)  Of these, only
  5501.     fopen() is widely portable, and access(), where it exists, must
  5502.     be used carefully if the program uses the Unix set-UID feature.
  5503.  
  5504.     Rather than trying to predict in advance whether an operation
  5505.     such as opening a file will succeed, it's often better to try
  5506.     it, check the return value, and complain if it fails.
  5507.     (Obviously, this approach won't work if you're trying to avoid
  5508.     overwriting an existing file, unless you've got something like
  5509.     the O_EXCL file opening option available, which does just what
  5510.     you want in this case.)
  5511.  
  5512.     References: PCS Sec. 12 pp. 189,213; POSIX Sec. 5.3.1,
  5513.     Sec. 5.6.2, Sec. 5.6.3.
  5514.  
  5515. 19.12:    How can I find out the size of a file, prior to reading it in?
  5516.  
  5517. A:    If the "size of a file" is the number of characters you'll be
  5518.     able to read from it in C, it is difficult or impossible to
  5519.     determine this number exactly).
  5520.  
  5521.     Under Unix, the stat() call will give you an exact answer.
  5522.     Several other systems supply a Unix-like stat() which will give
  5523.     an approximate answer.  You can fseek() to the end and then use
  5524.     ftell(), but these tend to have the same problems: fstat() is
  5525.     not portable, and generally tells you the same thing stat()
  5526.     tells you; ftell() is not guaranteed to return a byte count
  5527.     except for binary files.  Some systems provide routines called
  5528.     filesize() or filelength(), but these are not portable, either.
  5529.  
  5530.     Are you sure you have to determine the file's size in advance?
  5531.     Since the most accurate way of determining the size of a file as
  5532.     a C program will see it is to open the file and read it, perhaps
  5533.     you can rearrange the code to learn the size as it reads.
  5534.  
  5535.     References: ANSI Sec. 4.9.9.4; ISO Sec. 7.9.9.4; H&S
  5536.     Sec. 15.5.1; PCS Sec. 12 p. 213; POSIX Sec. 5.6.2.
  5537.  
  5538. 19.13:    How can a file be shortened in-place without completely clearing
  5539.     or rewriting it?
  5540.  
  5541. A:    BSD systems provide ftruncate(), several others supply chsize(),
  5542.     and a few may provide a (possibly undocumented) fcntl option
  5543.     F_FREESP.  Under MS-DOS, you can sometimes use write(fd, "", 0).
  5544.     However, there is no portable solution, nor a way to delete
  5545.     blocks at the beginning.  See also question 19.14.
  5546.  
  5547. 19.14:    How can I insert or delete a line (or record) in the middle of a
  5548.     file?
  5549.  
  5550. A:    Short of rewriting the file, you probably can't.  The usual
  5551.     solution is simply to rewrite the file.  (Instead of deleting
  5552.     records, you might consider simply marking them as deleted, to
  5553.     avoid rewriting.)  See also questions 12.30 and 19.13.
  5554.  
  5555. 19.15:    How can I recover the file name given an open stream or file
  5556.     descriptor?
  5557.  
  5558. A:    This problem is, in general, insoluble.  Under Unix, for
  5559.     instance, a scan of the entire disk (perhaps involving special
  5560.     permissions) would theoretically be required, and would fail if
  5561.     the descriptor were connected to a pipe or referred to a deleted
  5562.     file (and could give a misleading answer for a file with
  5563.     multiple links).  It is best to remember the names of files
  5564.     yourself when you open them (perhaps with a wrapper function
  5565.     around fopen()).
  5566.  
  5567. 19.16:    How can I delete a file?
  5568.  
  5569. A:    The Standard C Library function is remove().  (This is therefore
  5570.     one of the few questions in this section for which the answer is
  5571.     *not* "It's system-dependent.")  On older, pre-ANSI Unix
  5572.     systems, remove() may not exist, in which case you can try
  5573.     unlink().
  5574.  
  5575.     References: K&R2 Sec. B1.1 p. 242; ANSI Sec. 4.9.4.1; ISO
  5576.     Sec. 7.9.4.1; H&S Sec. 15.15 p. 382; PCS Sec. 12 pp. 208,220-
  5577.     221; POSIX Sec. 5.5.1, Sec. 8.2.4.
  5578.  
  5579. 19.17:    Why can't I open a file by its explicit path?  The call
  5580.  
  5581.         fopen("c:\newdir\file.dat", "r")
  5582.  
  5583.     is failing.
  5584.  
  5585. A:    The file you actually requested -- with the characters \n and \f
  5586.     in its name -- probably doesn't exist, and isn't what you
  5587.     thought you were trying to open.
  5588.  
  5589.     In character constants and string literals, the backslash \ is
  5590.     an escape character, giving special meaning to the character
  5591.     following it.  In order for literal backslashes in a pathname to
  5592.     be passed through to fopen() (or any other routine) correctly,
  5593.     they have to be doubled, so that the first backslash in each
  5594.     pair quotes the second one:
  5595.  
  5596.         fopen("c:\\newdir\\file.dat", "r");
  5597.  
  5598.     Alternatively, under MS-DOS, it turns out that forward slashes
  5599.     are also accepted as directory separators, so you could use
  5600.  
  5601.         fopen("c:/newdir/file.dat", "r");
  5602.  
  5603.     (Note, by the way, that header file names mentioned in
  5604.     preprocessor #include directives are *not* string literals, so
  5605.     you may not have to worry about backslashes there.)
  5606.  
  5607. 19.18:    I'm getting an error, "Too many open files".  How can I increase
  5608.     the allowable number of simultaneously open files?
  5609.  
  5610. A:    There are actually at least two resource limitations on the
  5611.     number of simultaneously open files: the number of low-level
  5612.     "file descriptors" or "file handles" available in the operating
  5613.     system, and the number of FILE structures available in the stdio
  5614.     library.  Both must be sufficient.  Under MS-DOS systems, you
  5615.     can control the number of operating system file handles with a
  5616.     line in CONFIG.SYS.  Some compilers come with instructions (and
  5617.     perhaps a source file or two) for increasing the number of stdio
  5618.     FILE structures.
  5619.  
  5620. 19.20:    How can I read a directory in a C program?
  5621.  
  5622. A:    See if you can use the opendir() and readdir() routines, which
  5623.     are part of the POSIX standard and are available on most Unix
  5624.     variants.  Implementations also exist for MS-DOS, VMS, and other
  5625.     systems.  (MS-DOS also has FINDFIRST and FINDNEXT routines which
  5626.     do essentially the same thing.)  readdir() only returns file
  5627.     names; if you need more information about the file, try calling
  5628.     stat().  To match filenames to some wildcard pattern, see
  5629.     question 13.7.
  5630.  
  5631.     References: K&R2 Sec. 8.6 pp. 179-184; PCS Sec. 13 pp. 230-1;
  5632.     POSIX Sec. 5.1; Schumacher, ed., _Software Solutions in C_
  5633.     Sec. 8.
  5634.  
  5635. 19.22:    How can I find out how much memory is available?
  5636.  
  5637. A:    Your operating system may provide a routine which returns this
  5638.     information, but it's quite system-dependent.
  5639.  
  5640. 19.23:    How can I allocate arrays or structures bigger than 64K?
  5641.  
  5642. A:    A reasonable computer ought to give you transparent access to
  5643.     all available memory.  If you're not so lucky, you'll either
  5644.     have to rethink your program's use of memory, or use various
  5645.     system-specific techniques.
  5646.  
  5647.     64K is (still) a pretty big chunk of memory.  No matter how much
  5648.     memory your computer has available, it's asking a lot to be able
  5649.     to allocate huge amounts of it contiguously.  (The C Standard
  5650.     does not guarantee that a single object can be larger than 32K.)
  5651.     Often it's a good idea to use data structures which don't
  5652.     require that all memory be contiguous.  For dynamically-
  5653.     allocated multidimensional arrays, you can use pointers to
  5654.     pointers, as illustrated in question 6.16.  Instead of a large
  5655.     array of structures, you can use a linked list, or an array of
  5656.     pointers to structures.
  5657.  
  5658.     If you're using a PC-compatible (8086-based) system, and running
  5659.     up against a 640K limit, consider using "huge" memory model, or
  5660.     expanded or extended memory, or malloc variants such as halloc()
  5661.     or farmalloc(), or a 32-bit "flat" compiler (e.g. djgpp, see
  5662.     question 18.3), or some kind of a DOS extender, or another
  5663.     operating system.
  5664.  
  5665.     References: ANSI Sec. 2.2.4.1; ISO Sec. 5.2.4.1.
  5666.  
  5667. 19.24:    What does the error message "DGROUP data allocation exceeds 64K"
  5668.     mean, and what can I do about it?  I thought that using large
  5669.     model meant that I could use more than 64K of data!
  5670.  
  5671. A:    Even in large memory models, MS-DOS compilers apparently toss
  5672.     certain data (strings, some initialized global or static
  5673.     variables) into a default data segment, and it's this segment
  5674.     that is overflowing.  Either use less global data, or, if you're
  5675.     already limiting yourself to reasonable amounts (and if the
  5676.     problem is due to something like the number of strings), you may
  5677.     be able to coax the compiler into not using the default data
  5678.     segment for so much.  Some compilers place only "small" data
  5679.     objects in the default data segment, and give you a way (e.g.
  5680.     the /Gt option under Microsoft compilers) to configure the
  5681.     threshold for "small."
  5682.  
  5683. 19.25:    How can I access memory (a memory-mapped device, or graphics
  5684.     memory) located at a certain address?
  5685.  
  5686. A:    Set a pointer, of the appropriate type, to the right number
  5687.     (using an explicit cast to assure the compiler that you really
  5688.     do intend this nonportable conversion):
  5689.  
  5690.         unsigned int *magicloc = (unsigned int *)0x12345678;
  5691.  
  5692.     Then, *magicloc refers to the location you want.  (Under MS-DOS,
  5693.     you may find a macro like MK_FP() handy for working with
  5694.     segments and offsets.)
  5695.  
  5696.     References: K&R1 Sec. A14.4 p. 210; K&R2 Sec. A6.6 p. 199; ANSI
  5697.     Sec. 3.3.4; ISO Sec. 6.3.4; Rationale Sec. 3.3.4; H&S Sec. 6.2.7
  5698.     pp. 171-2.
  5699.  
  5700. 19.27:    How can I invoke another program (a standalone executable, or an
  5701.     operating system command) from within a C program?
  5702.  
  5703. A:    Use the library function system(), which does exactly that.
  5704.     Note that system's return value is the command's exit status,
  5705.     and usually has nothing to do with the output of the command.
  5706.     Note also that system() accepts a single string representing the
  5707.     command to be invoked; if you need to build up a complex command
  5708.     line, you can use sprintf().  See also question 19.30.
  5709.  
  5710.     References: K&R1 Sec. 7.9 p. 157; K&R2 Sec. 7.8.4 p. 167,
  5711.     Sec. B6 p. 253; ANSI Sec. 4.10.4.5; ISO Sec. 7.10.4.5; H&S
  5712.     Sec. 19.2 p. 407; PCS Sec. 11 p. 179.
  5713.  
  5714. 19.30:    How can I invoke another program or command and trap its output?
  5715.  
  5716. A:    Unix and some other systems provide a popen() routine, which
  5717.     sets up a stdio stream on a pipe connected to the process
  5718.     running a command, so that the output can be read (or the input
  5719.     supplied).  (Also, remember to call pclose().)
  5720.  
  5721.     If you can't use popen(), you may be able to use system(), with
  5722.     the output going to a file which you then open and read.
  5723.  
  5724.     If you're using Unix and popen() isn't sufficient, you can learn
  5725.     about pipe(), dup(), fork(), and exec().
  5726.  
  5727.     (One thing that probably would *not* work, by the way, would be
  5728.     to use freopen().)
  5729.  
  5730.     References: PCS Sec. 11 p. 169.
  5731.  
  5732. 19.31:    How can my program discover the complete pathname to the
  5733.     executable from which it was invoked?
  5734.  
  5735. A:    argv[0] may contain all or part of the pathname, or it may
  5736.     contain nothing.  You may be able to duplicate the command
  5737.     language interpreter's search path logic to locate the
  5738.     executable if the name in argv[0] is present but incomplete.
  5739.     However, there is no guaranteed solution.
  5740.  
  5741.     References: K&R1 Sec. 5.11 p. 111; K&R2 Sec. 5.10 p. 115; ANSI
  5742.     Sec. 2.1.2.2.1; ISO Sec. 5.1.2.2.1; H&S Sec. 20.1 p. 416.
  5743.  
  5744. 19.32:    How can I automatically locate a program's configuration files
  5745.     in the same directory as the executable?
  5746.  
  5747. A:    It's hard; see also question 19.31 above.  Even if you can
  5748.     figure out a workable way to do it, you might want to consider
  5749.     making the program's auxiliary (library) directory configurable,
  5750.     perhaps with an environment variable.  (It's especially
  5751.     important to allow variable placement of a program's
  5752.     configuration files when the program will be used by several
  5753.     people, e.g. on a multiuser system.)
  5754.  
  5755. 19.33:    How can a process change an environment variable in its caller?
  5756.  
  5757. A:    It may or may not be possible to do so at all.  Different
  5758.     operating systems implement global name/value functionality
  5759.     similar to the Unix environment in different ways.  Whether the
  5760.     "environment" can be usefully altered by a running program, and
  5761.     if so, how, is system-dependent.
  5762.  
  5763.     Under Unix, a process can modify its own environment (some
  5764.     systems provide setenv() or putenv() functions for the purpose),
  5765.     and the modified environment is generally passed on to child
  5766.     processes, but it is *not* propagated back to the parent
  5767.     process.
  5768.  
  5769. 19.36:    How can I read in an object file and jump to routines in it?
  5770.  
  5771. A:    You want a dynamic linker or loader.  It may be possible to
  5772.     malloc some space and read in object files, but you have to know
  5773.     an awful lot about object file formats, relocation, etc.  Under
  5774.     BSD Unix, you could use system() and ld -A to do the linking for
  5775.     you.  Many versions of SunOS and System V have the -ldl library
  5776.     which allows object files to be dynamically loaded.  Under VMS,
  5777.     use LIB$FIND_IMAGE_SYMBOL.  GNU has a package called "dld".  See
  5778.     also question 15.13.
  5779.  
  5780. 19.37:    How can I implement a delay, or time a user's response, with sub-
  5781.     second resolution?
  5782.  
  5783. A:    Unfortunately, there is no portable way.  V7 Unix, and derived
  5784.     systems, provided a fairly useful ftime() routine with
  5785.     resolution up to a millisecond, but it has disappeared from
  5786.     System V and POSIX.  Other routines you might look for on your
  5787.     system include clock(), delay(), gettimeofday(), msleep(),
  5788.     nap(), napms(), setitimer(), sleep(), times(), and usleep().
  5789.     (A routine called wait(), however, is at least under Unix *not*
  5790.     what you want.)  The select() and poll() calls (if available)
  5791.     can be pressed into service to implement simple delays.  On MS-
  5792.     DOS machines, it is possible to reprogram the system timer and
  5793.     timer interrupts.
  5794.  
  5795.     Of these, only clock() is part of the ANSI Standard.  The
  5796.     difference between two calls to clock() gives elapsed execution
  5797.     time, and if CLOCKS_PER_SEC is greater than 1, the difference will
  5798.     have subsecond resolution.  However, clock() gives elapsed
  5799.     processor time used by the current program, which on a
  5800.     multitasking system may differ considerably from real time.
  5801.  
  5802.     If you're trying to implement a delay and all you have available
  5803.     is a time-reporting function, you can implement a CPU-intensive
  5804.     busy-wait, but this is only an option on a single-user, single-
  5805.     tasking machine as it is terribly antisocial to any other
  5806.     processes.  Under a multi-tasking operating system, be sure to
  5807.     use a call which puts your process to sleep for the duration,
  5808.     such as sleep() or select(), or pause() in conjunction with
  5809.     alarm() or setitimer().
  5810.  
  5811.     For really brief delays, it's tempting to use a do-nothing loop
  5812.     like
  5813.  
  5814.         long int i;
  5815.         for(i = 0; i < 1000000; i++)
  5816.             ;
  5817.  
  5818.     but resist this temptation if at all possible!  For one thing,
  5819.     your carefully-calculated delay loops will stop working next
  5820.     month when a faster processor comes out.  Perhaps worse, a
  5821.     clever compiler may notice that the loop does nothing and
  5822.     optimize it away completely.
  5823.  
  5824.     References: H&S Sec. 18.1 pp. 398-9; PCS Sec. 12 pp. 197-8,215-
  5825.     6; POSIX Sec. 4.5.2.
  5826.  
  5827. 19.38:    How can I trap or ignore keyboard interrupts like control-C?
  5828.  
  5829. A:    The basic step is to call signal(), either as
  5830.  
  5831.         #include <signal.h>
  5832.         signal(SIGINT, SIG_IGN);
  5833.  
  5834.     to ignore the interrupt signal, or as
  5835.  
  5836.         extern void func(int);
  5837.         signal(SIGINT, func);
  5838.  
  5839.     to cause control to transfer to function func() on receipt of an
  5840.     interrupt signal.
  5841.  
  5842.     On a multi-tasking system such as Unix, it's best to use a
  5843.     slightly more involved technique:
  5844.  
  5845.         extern void func(int);
  5846.         if(signal(SIGINT, SIG_IGN) != SIG_IGN)
  5847.             signal(SIGINT, func);
  5848.  
  5849.     The test and extra call ensure that a keyboard interrupt typed
  5850.     in the foreground won't inadvertently interrupt a program
  5851.     running in the background (and it doesn't hurt to code calls to
  5852.     signal() this way on any system).
  5853.  
  5854.     On some systems, keyboard interrupt handling is also a function
  5855.     of the mode of the terminal-input subsystem; see question 19.1.
  5856.     On some systems, checking for keyboard interrupts is only
  5857.     performed when the program is reading input, and keyboard
  5858.     interrupt handling may therefore depend on which input routines
  5859.     are being called (and *whether* any input routines are active at
  5860.     all).  On MS-DOS systems, setcbrk() or ctrlbrk() functions may
  5861.     also be involved.
  5862.  
  5863.     References: ANSI Secs. 4.7,4.7.1; ISO Secs. 7.7,7.7.1; H&S
  5864.     Sec. 19.6 pp. 411-3; PCS Sec. 12 pp. 210-2; POSIX
  5865.     Secs. 3.3.1,3.3.4.
  5866.  
  5867. 19.39:    How can I handle floating-point exceptions gracefully?
  5868.  
  5869. A:    On many systems, you can define a routine matherr() which will
  5870.     be called when there are certain floating-point errors, such as
  5871.     errors in the math routines in <math.h>.  You may also be able
  5872.     to use signal() (see question 19.38 above) to catch SIGFPE.  See
  5873.     also question 14.9.
  5874.  
  5875.     References: Rationale Sec. 4.5.1.
  5876.  
  5877. 19.40:    How do I...  Use sockets?  Do networking?  Write client/server
  5878.     applications?
  5879.  
  5880. A:    All of these questions are outside of the scope of this list and
  5881.     have much more to do with the networking facilities which you
  5882.     have available than they do with C.  Good books on the subject
  5883.     are Douglas Comer's three-volume _Internetworking with TCP/IP_
  5884.     and W. R. Stevens's _UNIX Network Programming_.  (There is also
  5885.     plenty of information out on the net itself.)
  5886.  
  5887. 19.40b: How do I use BIOS calls?  How can I write ISR's?  How can I
  5888.     create TSR's?
  5889.  
  5890. A:    These are very particular to specific systems (PC compatibles
  5891.     running MS-DOS, most likely).  You'll get much better
  5892.     information in a specific newsgroup such as
  5893.     comp.os.msdos.programmer or its FAQ list; another excellent
  5894.     resource is Ralf Brown's interrupt list.
  5895.  
  5896. 19.41:    But I can't use all these nonstandard, system-dependent
  5897.     functions, because my program has to be ANSI compatible!
  5898.  
  5899. A:    You're out of luck.  Either you misunderstood your requirement,
  5900.     or it's an impossible one to meet.  ANSI/ISO Standard C simply
  5901.     does not define ways of doing these things.  (POSIX defines a
  5902.     few.)  It is possible, and desirable, for *most* of a program to
  5903.     be ANSI-compatible, deferring the system-dependent functionality
  5904.     to a few routines in a few files which are rewritten for each
  5905.     system ported to.
  5906.  
  5907.  
  5908. Section 20. Miscellaneous
  5909.  
  5910. 20.1:    How can I return multiple values from a function?
  5911.  
  5912. A:    Either pass pointers to several locations which the function can
  5913.     fill in, or have the function return a structure containing the
  5914.     desired values, or (in a pinch) consider global variables.  See
  5915.     also questions 2.7, 4.8, and 7.5.
  5916.  
  5917. 20.3:    How do I access command-line arguments?
  5918.  
  5919. A:    They are pointed to by the argv array with which main() is
  5920.     called.
  5921.  
  5922.     References: K&R1 Sec. 5.11 pp. 110-114; K&R2 Sec. 5.10 pp. 114-
  5923.     118; ANSI Sec. 2.1.2.2.1; ISO Sec. 5.1.2.2.1; H&S Sec. 20.1 p.
  5924.     416; PCS Sec. 5.6 pp. 81-2, Sec. 11 p. 159, pp. 339-40 Appendix
  5925.     F; Schumacher, ed., _Software Solutions in C_ Sec. 4 pp. 75-85.
  5926.  
  5927. 20.5:    How can I write data files which can be read on other machines
  5928.     with different word size, byte order, or floating point formats?
  5929.  
  5930. A:    The most portable solution is to use text files (usually ASCII),
  5931.     written with fprintf() and read with fscanf() or the like.
  5932.     (Similar advice also applies to network protocols.)  Be
  5933.     skeptical of arguments which imply that text files are too big,
  5934.     or that reading and writing them is too slow.  Not only is their
  5935.     efficiency frequently acceptable in practice, but the advantages
  5936.     of being able to interchange them easily between machines, and
  5937.     manipulate them with standard tools, can be overwhelming.
  5938.  
  5939.     If you must use a binary format, you can improve portability,
  5940.     and perhaps take advantage of prewritten I/O libraries, by
  5941.     making use of standardized formats such as Sun's XDR (RFC 1014),
  5942.     OSI's ASN.1 (referenced in CCITT X.409 and ISO 8825 "Basic
  5943.     Encoding Rules"), CDF, netCDF, or HDF.  See also questions 2.12
  5944.     and 12.38.
  5945.  
  5946.     References: PCS Sec. 6 pp. 86,88.
  5947.  
  5948. 20.6:    If I have a char * variable pointing to the name of a function,
  5949.     how can I call that function?
  5950.  
  5951. A:    The most straightforward thing to do is to maintain a
  5952.     correspondence table of names and function pointers:
  5953.  
  5954.         int func(), anotherfunc();
  5955.  
  5956.         struct { char *name; int (*funcptr)(); } symtab[] = {
  5957.             "func",        func,
  5958.             "anotherfunc",    anotherfunc,
  5959.         };
  5960.  
  5961.     Then, search the table for the name, and call via the associated
  5962.     function pointer.  See also questions 2.15 and 19.36.
  5963.  
  5964.     References: PCS Sec. 11 p. 168.
  5965.  
  5966. 20.8:    How can I implement sets or arrays of bits?
  5967.  
  5968. A:    Use arrays of char or int, with a few macros to access the
  5969.     desired bit at the proper index.  Here are some simple macros to
  5970.     use with arrays of char:
  5971.  
  5972.         #include <limits.h>        /* for CHAR_BIT */
  5973.  
  5974.         #define BITMASK(b) (1 << ((b) % CHAR_BIT))
  5975.         #define BITSLOT(b) ((b) / CHAR_BIT)
  5976.         #define BITSET(a, b) ((a)[BITSLOT(b)] |= BITMASK(b))
  5977.         #define BITTEST(a, b) ((a)[BITSLOT(b)] & BITMASK(b))
  5978.  
  5979.     (If you don't have <limits.h>, try using 8 for CHAR_BIT.)
  5980.  
  5981.     References: H&S Sec. 7.6.7 pp. 211-216.
  5982.  
  5983. 20.9:    How can I determine whether a machine's byte order is big-endian
  5984.     or little-endian?
  5985.  
  5986. A:    One way is to use a pointer:
  5987.  
  5988.         int x = 1;
  5989.         if(*(char *)&x == 1)
  5990.             printf("little-endian\n");
  5991.         else    printf("big-endian\n");
  5992.  
  5993.     It's also possible to use a union.
  5994.  
  5995.     See also question 10.16.
  5996.  
  5997.     References: H&S Sec. 6.1.2 pp. 163-4.
  5998.  
  5999. 20.10:    How can I convert integers to binary or hexadecimal?
  6000.  
  6001. A:    Make sure you really know what you're asking.  Integers are
  6002.     stored internally in binary, although for most purposes it is
  6003.     not incorrect to think of them as being in octal, decimal, or
  6004.     hexadecimal, whichever is convenient.  The base in which a
  6005.     number is expressed matters only when that number is read in
  6006.     from or written out to the outside world.
  6007.  
  6008.     In source code, a non-decimal base is indicated by a leading 0
  6009.     or 0x (for octal or hexadecimal, respectively).  During I/O, the
  6010.     base of a formatted number is controlled in the printf and scanf
  6011.     family of functions by the choice of format specifier (%d, %o,
  6012.     %x, etc.) and in the strtol() and strtoul() functions by the
  6013.     third argument.  During *binary* I/O, however, the base again
  6014.     becomes immaterial.
  6015.  
  6016.     For more information about "binary" I/O, see question 2.11.  See
  6017.     also questions 8.6 and 13.1.
  6018.  
  6019.     References: ANSI Secs. 4.10.1.5,4.10.1.6; ISO
  6020.     Secs. 7.10.1.5,7.10.1.6.
  6021.  
  6022. 20.11:    Can I use base-2 constants (something like 0b101010)?
  6023.     Is there a printf() format for binary?
  6024.  
  6025. A:    No, on both counts.  You can convert base-2 string
  6026.     representations to integers with strtol().
  6027.  
  6028. 20.12:    What is the most efficient way to count the number of bits which
  6029.     are set in a value?
  6030.  
  6031. A:    Many "bit-fiddling" problems like this one can be sped up and
  6032.     streamlined using lookup tables (but see question 20.13 below).
  6033.  
  6034. 20.13:    How can I make my code more efficient?
  6035.  
  6036. A:    Efficiency, though a favorite comp.lang.c topic, is not
  6037.     important nearly as often as people tend to think it is.  Most
  6038.     of the code in most programs is not time-critical.  When code is
  6039.     not time-critical, it is far more important that it be written
  6040.     clearly and portably than that it be written maximally
  6041.     efficiently.  (Remember that computers are very, very fast, and
  6042.     that even "inefficient" code can run without apparent delay.)
  6043.  
  6044.     It is notoriously difficult to predict what the "hot spots" in a
  6045.     program will be.  When efficiency is a concern, it is important
  6046.     to use profiling software to determine which parts of the
  6047.     program deserve attention.  Often, actual computation time is
  6048.     swamped by peripheral tasks such as I/O and memory allocation,
  6049.     which can be sped up by using buffering and caching techniques.
  6050.  
  6051.     Even for code that *is* time-critical, it is not as important to
  6052.     "microoptimize" the coding details.  Many of the "efficient
  6053.     coding tricks" which are frequently suggested (e.g. substituting
  6054.     shift operators for multiplication by powers of two) are
  6055.     performed automatically by even simpleminded compilers.
  6056.     Heavyhanded optimization attempts can make code so bulky that
  6057.     performance is actually degraded, and are rarely portable (i.e.
  6058.     they may speed things up on one machine but slow them down on
  6059.     another).  In any case, tweaking the coding usually results in
  6060.     at best linear performance improvements; the big payoffs are in
  6061.     better algorithms.
  6062.  
  6063.     For more discussion of efficiency tradeoffs, as well as good
  6064.     advice on how to improve efficiency when it is important, see
  6065.     chapter 7 of Kernighan and Plauger's _The Elements of
  6066.     Programming Style_, and Jon Bentley's _Writing Efficient
  6067.     Programs_.
  6068.  
  6069. 20.14:    Are pointers really faster than arrays?  How much do function
  6070.     calls slow things down?  Is ++i faster than i = i + 1?
  6071.  
  6072. A:    Precise answers to these and many similar questions depend of
  6073.     course on the processor and compiler in use.  If you simply must
  6074.     know, you'll have to time test programs carefully.  (Often the
  6075.     differences are so slight that hundreds of thousands of
  6076.     iterations are required even to see them.  Check the compiler's
  6077.     assembly language output, if available, to see if two purported
  6078.     alternatives aren't compiled identically.)
  6079.  
  6080.     It is "usually" faster to march through large arrays with
  6081.     pointers rather than array subscripts, but for some processors
  6082.     the reverse is true.
  6083.  
  6084.     Function calls, though obviously incrementally slower than in-
  6085.     line code, contribute so much to modularity and code clarity
  6086.     that there is rarely good reason to avoid them.
  6087.  
  6088.     Before rearranging expressions such as i = i + 1, remember that
  6089.     you are dealing with a compiler, not a keystroke-programmable
  6090.     calculator.  Any decent compiler will generate identical code
  6091.     for ++i, i += 1, and i = i + 1.  The reasons for using ++i or
  6092.     i += 1 over i = i + 1 have to do with style, not efficiency.
  6093.     (See also question 3.12.)
  6094.  
  6095. 20.17:    Is there a way to switch on strings?
  6096.  
  6097. A:    Not directly.  Sometimes, it's appropriate to use a separate
  6098.     function to map strings to integer codes, and then switch on
  6099.     those.  Otherwise, of course, you can fall back on strcmp() and
  6100.     a conventional if/else chain.  See also questions 10.12, 20.18,
  6101.     and 20.29.
  6102.  
  6103.     References: K&R1 Sec. 3.4 p. 55; K&R2 Sec. 3.4 p. 58; ANSI
  6104.     Sec. 3.6.4.2; ISO Sec. 6.6.4.2; H&S Sec. 8.7 p. 248.
  6105.  
  6106. 20.18:    Is there a way to have non-constant case labels (i.e. ranges or
  6107.     arbitrary expressions)?
  6108.  
  6109. A:    No.  The switch statement was originally designed to be quite
  6110.     simple for the compiler to translate, therefore case labels are
  6111.     limited to single, constant, integral expressions.  You *can*
  6112.     attach several case labels to the same statement, which will let
  6113.     you cover a small range if you don't mind listing all cases
  6114.     explicitly.
  6115.  
  6116.     If you want to select on arbitrary ranges or non-constant
  6117.     expressions, you'll have to use an if/else chain.
  6118.  
  6119.     See also questions question 20.17.
  6120.  
  6121.     References: K&R1 Sec. 3.4 p. 55; K&R2 Sec. 3.4 p. 58; ANSI
  6122.     Sec. 3.6.4.2; ISO Sec. 6.6.4.2; Rationale Sec. 3.6.4.2; H&S
  6123.     Sec. 8.7 p. 248.
  6124.  
  6125. 20.19:    Are the outer parentheses in return statements really optional?
  6126.  
  6127. A:    Yes.
  6128.  
  6129.     Long ago, in the early days of C, they were required, and just
  6130.     enough people learned C then, and wrote code which is still in
  6131.     circulation, that the notion that they might still be required
  6132.     is widespread.
  6133.  
  6134.     (As it happens, parentheses are optional with the sizeof
  6135.     operator, too, as long as its operand is a variable or a unary
  6136.     expression.)
  6137.  
  6138.     References: K&R1 Sec. A18.3 p. 218; ANSI Sec. 3.3.3, Sec. 3.6.6;
  6139.     ISO Sec. 6.3.3, Sec. 6.6.6; H&S Sec. 8.9 p. 254.
  6140.  
  6141. 20.20:    Why don't C comments nest?  How am I supposed to comment out
  6142.     code containing comments?  Are comments legal inside quoted
  6143.     strings?
  6144.  
  6145. A:    C comments don't nest mostly because PL/I's comments, which C's
  6146.     are borrowed from, don't either.  Therefore, it is usually
  6147.     better to "comment out" large sections of code, which might
  6148.     contain comments, with #ifdef or #if 0 (but see question 11.19).
  6149.  
  6150.     The character sequences /* and */ are not special within double-
  6151.     quoted strings, and do not therefore introduce comments, because
  6152.     a program (particularly one which is generating C code as
  6153.     output) might want to print them.
  6154.  
  6155.     Note also that // comments, as in C++, are not currently legal
  6156.     in C, so it's not a good idea to use them in C programs (even if
  6157.     your compiler supports them as an extension).
  6158.  
  6159.     References: K&R1 Sec. A2.1 p. 179; K&R2 Sec. A2.2 p. 192; ANSI
  6160.     Sec. 3.1.9 (esp. footnote 26), Appendix E; ISO Sec. 6.1.9, Annex
  6161.     F; Rationale Sec. 3.1.9; H&S Sec. 2.2 pp. 18-9; PCS Sec. 10 p.
  6162.     130.
  6163.  
  6164. 20.24:    Why doesn't C have nested functions?
  6165.  
  6166. A:    It's not trivial to implement nested functions such that they
  6167.     have the proper access to local variables in the containing
  6168.     function(s), so they were deliberately left out of C as a
  6169.     simplification.  (gcc does allow them, as an extension.)  For
  6170.     many potential uses of nested functions (e.g. qsort comparison
  6171.     functions), an adequate if slightly cumbersome solution is to
  6172.     use an adjacent function with static declaration, communicating
  6173.     if necessary via a few static variables.  (A cleaner solution
  6174.     when such functions must communicate is to pass around a pointer
  6175.     to a structure containing the necessary context.)
  6176.  
  6177. 20.25:    How can I call FORTRAN (C++, BASIC, Pascal, Ada, LISP) functions
  6178.     from C?  (And vice versa?)
  6179.  
  6180. A:    The answer is entirely dependent on the machine and the specific
  6181.     calling sequences of the various compilers in use, and may not
  6182.     be possible at all.  Read your compiler documentation very
  6183.     carefully; sometimes there is a "mixed-language programming
  6184.     guide," although the techniques for passing arguments and
  6185.     ensuring correct run-time startup are often arcane.  More
  6186.     information may be found in FORT.gz by Glenn Geers, available
  6187.     via anonymous ftp from suphys.physics.su.oz.au in the src
  6188.     directory.
  6189.  
  6190.     cfortran.h, a C header file, simplifies C/FORTRAN interfacing on
  6191.     many popular machines.  It is available via anonymous ftp from
  6192.     zebra.desy.de (131.169.2.244).
  6193.  
  6194.     In C++, a "C" modifier in an external function declaration
  6195.     indicates that the function is to be called using C calling
  6196.     conventions.
  6197.  
  6198.     References: H&S Sec. 4.9.8 pp. 106-7.
  6199.  
  6200. 20.26:    Does anyone know of a program for converting Pascal or FORTRAN
  6201.     (or LISP, Ada, awk, "Old" C, ...) to C?
  6202.  
  6203. A:    Several freely distributable programs are available:
  6204.  
  6205.     p2c    A Pascal to C converter written by Dave Gillespie,
  6206.         posted to comp.sources.unix in March, 1990 (Volume 21);
  6207.         also available by anonymous ftp from
  6208.         csvax.cs.caltech.edu, file pub/p2c-1.20.tar.Z .
  6209.  
  6210.     ptoc    Another Pascal to C converter, this one written in
  6211.         Pascal (comp.sources.unix, Volume 10, also patches in
  6212.         Volume 13?).
  6213.  
  6214.     f2c    A Fortran to C converter jointly developed by people
  6215.         from Bell Labs, Bellcore, and Carnegie Mellon.  To find
  6216.         out more about f2c, send the mail message "send index
  6217.         from f2c" to netlib@research.att.com or research!netlib.
  6218.         (It is also available via anonymous ftp on
  6219.         netlib.att.com, in directory netlib/f2c.)
  6220.  
  6221.     This FAQ list's maintainer also has available a list of a few
  6222.     other commercial translation products, and some for more obscure
  6223.     languages.
  6224.  
  6225.     See also questions 11.31 and 18.16.
  6226.  
  6227. 20.27:    Is C++ a superset of C?  Can I use a C++ compiler to compile C
  6228.     code?
  6229.  
  6230. A:    C++ was derived from C, and is largely based on it, but there
  6231.     are some legal C constructs which are not legal C++.
  6232.     Conversely, ANSI C inherited several features from C++,
  6233.     including prototypes and const, so neither language is really a
  6234.     subset or superset of the other.  In spite of the differences,
  6235.     many C programs will compile correctly in a C++ environment, and
  6236.     many recent compilers offer both C and C++ compilation modes.
  6237.  
  6238.     References: H&S p. xviii, Sec. 1.1.5 p. 6, Sec. 2.8 pp. 36-7,
  6239.     Sec. 4.9 pp. 104-107.
  6240.  
  6241. 20.28:    I need a sort of an "approximate" strcmp routine, for comparing
  6242.     two strings for close, but not necessarily exact, equality.
  6243.  
  6244. A:    Some nice information and algorithms having to do with
  6245.     approximate string matching, as well as a useful bibliography,
  6246.     can be found in Sun Wu and Udi Manber's paper "AGREP -- A Fast
  6247.     Approximate Pattern-Matching Tool."
  6248.  
  6249.     Another approach involves the "soundex" algorithm, which maps
  6250.     similar-sounding words to the same codes.  Soundex was designed
  6251.     for discovering similar-sounding names (for telephone directory
  6252.     assistance, as it happens), but it can be pressed into service
  6253.     for processing arbitrary words.
  6254.  
  6255.     References: Knuth Sec. 6 pp. 391-2 Volume 3; Wu and Manber,
  6256.     "AGREP -- A Fast Approximate Pattern-Matching Tool" .
  6257.  
  6258. 20.29:    What is hashing?
  6259.  
  6260. A:    Hashing is the process of mapping strings to integers, usually
  6261.     in a relatively small range.  A "hash function" maps a string
  6262.     (or some other data structure) to a a bounded number (the "hash
  6263.     bucket") which can more easily be used as an index in an array,
  6264.     or for performing repeated comparisons.  (Obviously, a mapping
  6265.     from a potentially huge set of strings to a small set of
  6266.     integers will not be unique.  Any algorithm using hashing
  6267.     therefore has to deal with the possibility of "collisions.")
  6268.     Many hashing functions and related algorithms have been
  6269.     developed; a full treatment is beyond the scope of this list.
  6270.  
  6271.     References: K&R2 Sec. 6.6; Knuth Sec. 6.4 pp. 506-549 Volume 3;
  6272.     Sedgewick Sec. 16 pp. 231-244.
  6273.  
  6274. 20.31:    How can I find the day of the week given the date?
  6275.  
  6276. A:    Use mktime() or localtime() (see questions 13.13 and 13.14, but
  6277.     beware of DST adjustments if tm_hour is 0), or Zeller's
  6278.     congruence (see the sci.math FAQ list), or this elegant code by
  6279.     Tomohiko Sakamoto:
  6280.  
  6281.         dayofweek(y, m, d)    /* 0 = Sunday */
  6282.         int y, m, d;        /* 1 <= m <= 12, y > 1752 or so */
  6283.         {
  6284.             static int t[] = {0, 3, 2, 5, 0, 3, 5, 1, 4, 6, 2, 4};
  6285.             y -= m < 3;
  6286.             return (y + y/4 - y/100 + y/400 + t[m-1] + d) % 7;
  6287.         }
  6288.  
  6289.     See also questions 13.14 and 20.32.
  6290.  
  6291.     References: ANSI Sec. 4.12.2.3; ISO Sec. 7.12.2.3.
  6292.  
  6293. 20.32:    Will 2000 be a leap year?  Is (year % 4 == 0) an accurate test
  6294.     for leap years?
  6295.  
  6296. A:    Yes and no, respectively.  The full expression for the present
  6297.     Gregorian calendar is
  6298.  
  6299.         year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)
  6300.  
  6301.     See a good astronomical almanac or other reference for details.
  6302.     (To forestall an eternal debate: references which claim the
  6303.     existence of a 4000-year rule are wrong.)
  6304.  
  6305. 20.34:    Here's a good puzzle: how do you write a program which produces
  6306.     its own source code as its output?
  6307.  
  6308. A:    It is actually quite difficult to write a self-reproducing
  6309.     program that is truly portable, due particularly to quoting and
  6310.     character set difficulties.
  6311.  
  6312.     Here is a classic example (which is normally presented on one
  6313.     line, although it will "fix" itself the first time it's run):
  6314.  
  6315.         char*s="char*s=%c%s%c;main(){printf(s,34,s,34);}";
  6316.         main(){printf(s,34,s,34);}
  6317.  
  6318.     (This program, like many of the genre, assumes that the double-
  6319.     quote character " has the value 34, as it does in ASCII.)
  6320.  
  6321. 20.35:    What is "Duff's Device"?
  6322.  
  6323. A:    It's a devastatingly deviously unrolled byte-copying loop,
  6324.     devised by Tom Duff while he was at Lucasfilm.  In its "classic"
  6325.     form, it looks like:
  6326.  
  6327.         register n = (count + 7) / 8;    /* count > 0 assumed */
  6328.         switch (count % 8)
  6329.         {
  6330.         case 0:    do { *to = *from++;
  6331.         case 7:        *to = *from++;
  6332.         case 6:         *to = *from++;
  6333.         case 5:        *to = *from++;
  6334.         case 4:        *to = *from++;
  6335.         case 3:        *to = *from++;
  6336.         case 2:        *to = *from++;
  6337.         case 1:        *to = *from++;
  6338.                    } while (--n > 0);
  6339.         }
  6340.  
  6341.     where count bytes are to be copied from the array pointed to by
  6342.     from to the memory location pointed to by to (which is a memory-
  6343.     mapped device output register, which is why to isn't
  6344.     incremented).  It solves the problem of handling the leftover
  6345.     bytes (when count isn't a multiple of 8) by interleaving a
  6346.     switch statement with the loop which copies bytes 8 at a time.
  6347.     (Believe it or not, it *is* legal to have case labels buried
  6348.     within blocks nested in a switch statement like this.  In his
  6349.     announcement of the technique to C's developers and the world,
  6350.     Duff noted that C's switch syntax, in particular its "fall
  6351.     through" behavior, had long been controversial, and that "This
  6352.     code forms some sort of argument in that debate, but I'm not
  6353.     sure whether it's for or against.")
  6354.  
  6355. 20.36:    When will the next International Obfuscated C Code Contest
  6356.     (IOCCC) be held?  How can I get a copy of the current and
  6357.     previous winning entries?
  6358.  
  6359. A:    The contest schedule is tied to the dates of the USENIX
  6360.     conferences at which the winners are announced.  At the time of
  6361.     this writing, it is expected that the yearly contest will open
  6362.     in October.  To obtain a current copy of the rules and
  6363.     guidelines, send e-mail with the Subject: line "send rules" to:
  6364.  
  6365.         {apple,pyramid,sun,uunet}!hoptoad!judges  or
  6366.         judges@toad.com
  6367.  
  6368.     (Note that these are *not* the addresses for submitting
  6369.     entries.)
  6370.  
  6371.     Contest winners should be announced at the winter USENIX
  6372.     conference in January, and are posted to the net sometime
  6373.     thereafter.  Winning entries from previous years (back to 1984)
  6374.     are archived at ftp.uu.net (see question 18.16) under the
  6375.     directory pub/ioccc/.
  6376.  
  6377.     As a last resort, previous winners may be obtained by sending e-
  6378.     mail to the above address, using the Subject: "send YEAR
  6379.     winners", where YEAR is a single four-digit year, a year range,
  6380.     or "all".
  6381.  
  6382. 20.37:    What was the entry keyword mentioned in K&R1?
  6383.  
  6384. A:    It was reserved to allow the possibility of having functions
  6385.     with multiple, differently-named entry points, a la FORTRAN.  It
  6386.     was not, to anyone's knowledge, ever implemented (nor does
  6387.     anyone remember what sort of syntax might have been imagined for
  6388.     it).  It has been withdrawn, and is not a keyword in ANSI C.
  6389.     (See also question 1.12.)
  6390.  
  6391.     References: K&R2 p. 259 Appendix C.
  6392.  
  6393. 20.38:    Where does the name "C" come from, anyway?
  6394.  
  6395. A:    C was derived from Ken Thompson's experimental language B, which
  6396.     was inspired by Martin Richards's BCPL (Basic Combined
  6397.     Programming Language), which was a simplification of CPL
  6398.     (Cambridge Programming Language).  For a while, there was
  6399.     speculation that C's successor might be named P (the third
  6400.     letter in BCPL) instead of D, but of course the most visible
  6401.     descendant language today is C++.
  6402.  
  6403. 20.39:    How do you pronounce "char"?
  6404.  
  6405. A:    You can pronounce the C keyword "char" in at least three ways:
  6406.     like the English words "char," "care," or "car;" the choice is
  6407.     arbitrary.
  6408.  
  6409. 20.40:    Where can I get extra copies of this list?  What about back
  6410.     issues?
  6411.  
  6412. A:    An up-to-date copy may be obtained from ftp.eskimo.com in
  6413.     directory u/s/scs/C-faq/.  You can also just pull it off the
  6414.     net; it is normally posted to comp.lang.c on the first of each
  6415.     month, with an Expires: line which should keep it around all
  6416.     month.  A parallel, abridged version is available (and posted),
  6417.     as is a list of changes accompanying each significantly updated
  6418.     version.
  6419.  
  6420.     The various versions of this list are also posted to the
  6421.     newsgroups comp.answers and news.answers .  Several sites
  6422.     archive news.answers postings and other FAQ lists, including
  6423.     this one; two sites are rtfm.mit.edu (directories
  6424.     pub/usenet/news.answers/C-faq/ and pub/usenet/comp.lang.c/) and
  6425.     ftp.uu.net (directory usenet/news.answers/C-faq/).  An archie
  6426.     server (see question 18.16) should help you find others; ask it
  6427.     to "find C-faq".  If you don't have ftp access, a mailserver at
  6428.     rtfm.mit.edu can mail you FAQ lists: send a message containing
  6429.     the single word help to mail-server@rtfm.mit.edu .  See the meta-
  6430.     FAQ list in news.answers for more information.
  6431.  
  6432.     A hypertext (HTML) version of this FAQ list is available on the
  6433.     World-Wide Web; the URL is http://www.eskimo.com/~scs/C-faq.top.html .
  6434.     URL's pointing at all FAQ lists (these may also allow topic
  6435.     searching) are http://www.cis.ohio-
  6436.     state.edu/hypertext/faq/usenet/FAQ-List.html and
  6437.     http://www.luth.se/wais/ .
  6438.  
  6439.     An extended version of this FAQ list is being published by
  6440.     Addison-Wesley as _C Programming FAQs: Frequently Asked
  6441.     Questions_ (ISBN 0-201-84519-9).  It should be available in
  6442.     November 1995.
  6443.  
  6444.     This list is an evolving document of questions which have been
  6445.     Frequent since before the Great Renaming, not just a collection
  6446.     of this month's interesting questions.  Older copies are
  6447.     obsolete and don't contain much, except the occasional typo,
  6448.     that the current list doesn't.
  6449.  
  6450.  
  6451. Bibliography
  6452.  
  6453. Americal National Standards Institute, _American National Standard for
  6454. Information Systems -- Programming Language -- C_, ANSI X3.159-1989 (see
  6455. question 11.2).  [ANSI]
  6456.  
  6457. Americal National Standards Institute, _Rationale for American National
  6458. Standard for Information Systems -- Programming Language -- C_ (see
  6459. question 11.2).  [Rationale]
  6460.  
  6461. Jon Bentley, _Writing Efficient Programs_, Prentice-Hall, 1982, ISBN 0-
  6462. 13-970244-X.
  6463.  
  6464. G.E.P. Box and Mervin E. Muller, "A Note on the Generation of Random
  6465. Normal Deviates," _Annals of Mathematical Statistics_, Vol. 29 #2, June,
  6466. 1958, pp. 610-611.
  6467.  
  6468. David Burki, "Date Conversions," _The C Users Journal_, February 1993,
  6469. pp. 29-34.
  6470.  
  6471. Ian F. Darwin, _Checking C Programs with lint_, O'Reilly, 1988, ISBN 0-
  6472. 937175-30-7.
  6473.  
  6474. David Goldberg, "What Every Computer Scientist Should Know about
  6475. Floating-Point Arithmetic," _ACM Computing Surveys_, Vol. 23 #1, March,
  6476. 1991, pp. 5-48.
  6477.  
  6478. Samuel P. Harbison and Guy L. Steele, Jr., _C: A Reference Manual_,
  6479. Fourth Edition, Prentice-Hall, 1995, ISBN 0-13-326224-3.  [H&S]
  6480.  
  6481. Mark R. Horton, _Portable C Software_, Prentice Hall, 1990, ISBN 0-13-
  6482. 868050-7.  [PCS]
  6483.  
  6484. Institute of Electrical and Electronics Engineers, _Portable Operating
  6485. System Interface (POSIX) -- Part 1: System Application Program Interface
  6486. (API) [C Language_, IEEE Std. 1003.1, ISO/IEC 9945-1.
  6487.  
  6488. International Organization for Standardization, ISO 9899:1990 (see
  6489. question 11.2).  [ISO]
  6490.  
  6491. Brian W. Kernighan and P.J. Plauger, _The Elements of Programming
  6492. Style_, Second Edition, McGraw-Hill, 1978, ISBN 0-07-034207-5.
  6493.  
  6494. Brian W. Kernighan and Dennis M. Ritchie, _The C Programming Language_,
  6495. Prentice-Hall, 1978, ISBN 0-13-110163-3.  [K&R1]
  6496.  
  6497. Brian W. Kernighan and Dennis M. Ritchie, _The C Programming Language_,
  6498. Second Edition, Prentice Hall, 1988, ISBN 0-13-110362-8, 0-13-110370-9.
  6499. [K&R2]
  6500.  
  6501. Donald E. Knuth, _The Art of Computer Programming_.  Volume 1:
  6502. _Fundamental Algorithms_, Second Edition, Addison-Wesley, 1973, ISBN 0-
  6503. 201-03809-9.  Volume 2: _Seminumerical Algorithms_, Second Edition,
  6504. Addison-Wesley, 1981, ISBN 0-201-03822-6.  Volume 3: _Sorting and
  6505. Searching_, Addison-Wesley, 1973, ISBN 0-201-03803-X.  [Knuth]
  6506.  
  6507. Andrew Koenig, _C Traps and Pitfalls_, Addison-Wesley, 1989, ISBN 0-201-
  6508. 17928-8.  [CT&P]
  6509.  
  6510. Stephen K. Park and Keith W. Miller, "Random Number Generators: Good
  6511. Ones are Hard to Find," _Communications of the ACM_, Vol. 31 #10,
  6512. October, 1988, pp. 1192-1201 (also technical correspondence August,
  6513. 1989, pp. 1020-1024, and July, 1993, pp. 108-110).
  6514.  
  6515. P.J. Plauger, _The Standard C Library_, Prentice Hall, 1992, ISBN 0-13-
  6516. 131509-9.
  6517.  
  6518. Thomas Plum, _C Programming Guidelines_, Second Edition, Plum Hall,
  6519. 1989, ISBN 0-911537-07-4.
  6520.  
  6521. William H. Press, Saul A. Teukolsky, William T. Vetterling, and Brian P.
  6522. Flannery, _Numerical Recipes in C_, Second Edition, Cambridge University
  6523. Press, 1992, ISBN 0-521-43108-5.
  6524.  
  6525. Dale Schumacher, Ed., _Software Solutions in C_, AP Professional, 1994,
  6526. ISBN 0-12-632360-7.
  6527.  
  6528. Robert Sedgewick, _Algorithms in C_, Addison-Wesley, 1990, ISBN 0-201-
  6529. 51425-7.
  6530.  
  6531. Charles Simonyi and Martin Heller, "The Hungarian Revolution," _Byte_,
  6532. August, 1991, pp.131-138.
  6533.  
  6534. David Straker, _C Style: Standards and Guidelines_, Prentice Hall, ISBN
  6535. 0-13-116898-3.
  6536.  
  6537. Steve Summit, _C Programming FAQs: Frequently Asked Questions_, Addison-
  6538. Wesley, 1995, ISBN 0-201-84519-9.  [The book version of this FAQ list.]
  6539.  
  6540. Sun Wu and Udi Manber, "AGREP -- A Fast Approximate Pattern-Matching
  6541. Tool," USENIX Conference Proceedings, Winter, 1992, pp. 153-162.
  6542.  
  6543. There is another bibliography in the revised Indian Hill style guide
  6544. (see question 17.9).  See also question 18.10.
  6545.  
  6546.  
  6547. Acknowledgements
  6548.  
  6549. Thanks to Jamshid Afshar, David Anderson, Tanner Andrews, Sudheer Apte,
  6550. Joseph Arceneaux, Randall Atkinson, Rick Beem, Peter Bennett, Wayne
  6551. Berke, Dan Bernstein, Tanmoy Bhattacharya, John Bickers, Gary Blaine,
  6552. Yuan Bo, Dave Boutcher, Michael Bresnahan, Vincent Broman, Stan Brown,
  6553. Joe Buehler, Kimberley Burchett, Gordon Burditt, Burkhard Burow, Conor
  6554. P. Cahill, D'Arcy J.M. Cain, Christopher Calabrese, Ian Cargill, Vinit
  6555. Carpenter, Paul Carter, Mike Chambers, Billy Chambless, Franklin Chen,
  6556. Jonathan Chen, Raymond Chen, Richard Cheung, Steve Clamage, Ken Corbin,
  6557. Ian Cottam, Russ Cox, Jonathan Coxhead, Lee Crawford, Steve Dahmer,
  6558. Andrew Daviel, James Davies, John E. Davis, Ken Delong,
  6559. Norm Diamond, Jeff Dunlop, Ray Dunn, Stephen M. Dunn, Michael J. Eager,
  6560. Scott Ehrlich, Arno Eigenwillig, Dave Eisen, Bjorn Engsig, David Evans,
  6561. Clive D.W. Feather, Dominic Feeley, Simao Ferraz, Chris Flatters, Rod
  6562. Flores, Alexander Forst, Steve Fosdick, Jeff Francis, Tom Gambill, Dave
  6563. Gillespie, Samuel Goldstein, Tim Goodwin, Alasdair Grant, Ron Guilmette,
  6564. Doug Gwyn, Michael Hafner, Tony Hansen, Elliotte Rusty Harold, Joe
  6565. Harrington, Des Herriott, Guy Harris, John Hascall, Ger Hobbelt, Jos
  6566. Horsmeier, Blair Houghton, James C. Hu, Chin Huang, David Hurt, Einar
  6567. Indridason, Vladimir Ivanovic, Jon Jagger, Ke Jin, Kirk Johnson, Larry
  6568. Jones, Arjan Kenter, James Kew, Lawrence Kirby, Kin-ichi Kitano, Peter
  6569. Klausler, Andrew Koenig, Tom Koenig, Adam Kolawa, Jukka Korpela, Ajoy
  6570. Krishnan T, Markus Kuhn, Deepak Kulkarni, Oliver Laumann, John Lauro,
  6571. Felix Lee, Mike Lee, Timothy J. Lee, Tony Lee, Marty Leisner, Don Libes,
  6572. Brian Liedtke, Philip Lijnzaad, Keith Lindsay, Yen-Wei Liu, Paul Long,
  6573. Christopher Lott, Tim Love, Tim McDaniel, Kevin McMahon, Stuart
  6574. MacMartin, John R. MacMillan, Andrew Main, Bob Makowski, Evan Manning,
  6575. Barry Margolin, George Matas, Brad Mears, Roger Miller, Bill Mitchell,
  6576. Mark Moraes, Darren Morby, Bernhard Muenzer, David Murphy, Walter
  6577. Murray, Ralf Muschall, Ken Nakata, Todd Nathan, Landon Curt Noll, Tim
  6578. Norman, Paul Nulsen, David O'Brien, Richard A. O'Keefe, Adam Kolawa,
  6579. James Ojaste, Hans Olsson, Bob Peck, Andrew Phillips, Christopher
  6580. Phillips, Francois Pinard, Nick Pitfield, Wayne Pollock, Dan Pop, Lutz
  6581. Prechelt, Lynn Pye, Kevin D. Quitt, Pat Rankin, Arjun Ray, Eric S.
  6582. Raymond, Peter W. Richards, Eric Roode, Manfred Rosenboom, J. M.
  6583. Rosenstock, Rick Rowe, Erkki Ruohtula, John Rushford, Kadda Sahnine,
  6584. Tomohiko Sakamoto, Matthew Saltzman, Rich Salz, Chip Salzenberg, Matthew
  6585. Sams, Paul Sand, DaviD W. Sanderson, Frank Sandy, Christopher Sawtell,
  6586. Jonas Schlein, Paul Schlyter, Doug Schmidt, Rene Schmit, Russell Schulz,
  6587. Dean Schulze, Chris Sears, Patricia Shanahan, Raymond Shwake, Peter da
  6588. Silva, Joshua Simons, Ross Smith, Henri Socha, Leslie J. Somos, Henry
  6589. Spencer, David Spuler, James Stern, Bob Stout, Steve Sullivan, Melanie
  6590. Summit, Erik Talvola, Dave Taylor, Clarke Thatcher, Wayne Throop, Chris
  6591. Torek, Steve Traugott, Ilya Tsindlekht, Andrew Tucker, Goran Uddeborg,
  6592. Rodrigo Vanegas, Jim Van Zandt, Wietse Venema, Tom Verhoeff, Ed
  6593. Vielmetti, Larry Virden, Chris Volpe, Mark Warren, Alan Watson, Kurt
  6594. Watzka, Larry Weiss, Martin Weitzel, Howard West, Tom White, Freek
  6595. Wiedijk, Dik T. Winter, Lars Wirzenius, Dave Wolverton, Mitch Wright,
  6596. Conway Yee, Ozan S. Yigit, and Zhuo Zang, who have contributed, directly
  6597. or indirectly, to this article.  Special thanks to Karl Heuer, Jutta
  6598. Degener, and particularly to Mark Brader, who (to borrow a line from
  6599. Steve Johnson) have goaded me beyond my inclination, and occasionally
  6600. beyond my endurance, in relentless pursuit of a better FAQ list.
  6601.  
  6602.                     Steve Summit
  6603.                     scs@eskimo.com
  6604.  
  6605. This article is Copyright 1988, 1990-1995 by Steve Summit.
  6606. Content from the book _C Programming FAQs: Frequently Asked Questions_
  6607. is made available here by permission of the author and the publisher as
  6608. a service to the community.  It is intended to complement the use of the
  6609. published text and is protected by international copyright laws.  The
  6610. content is made available here and may be accessed freely for personal
  6611. use but may not be published or retransmitted without written
  6612. permission.
  6613. The C code in this article (vstrcat(), error(), etc.) is public domain
  6614. and may be used without restriction.
  6615.